开发者

Django Dropdown populate from database

开发者_JAVA百科

If I pass items to the template through the view, and I want the user to select one of the values that gets submitted to a user's record, I would only have dun a for loop in the template right?

What would that look like? In the template:

<form method="POST" 
<select>

</select>
</form>

Model:

class UserItem(models.Model):
    user = models.ForeignKey(User)
    item = models.ForeignKey(Item)


class Item(models.Model):
    name = models.CharField(max_length = 50)
    condition = models.CharField(max_length = 50)

View:

def selectview(request):
   item  = Item.objects.filter()
   form = request.POST
   if form.is_valid():
      # SAVE 

   return render_to_response (
   'select/item.html',
    {'item':item},
    context_instance = RequestContext(request)
               )


If I understood your need correctly, you can do something like:

<form method="POST">
<select name="item_id">
{% for entry in items %}
    <option value="{{ entry.id }}">{{ entry.name }}</option>
{% endfor %}
</select>
</form>

By the way, you should give the name items instead of item, since it's a collection (but it's just a remark ;)).

Doing so, you will have a list of all the items in the database.

Then, in the post, here what you need to do:

def selectview(request):
   item  = Item.objects.all() # use filter() when you have sth to filter ;)
   form = request.POST # you seem to misinterpret the use of form from django and POST data. you should take a look at [Django with forms][1]
   # you can remove the preview assignment (form =request.POST)
   if request.method == 'POST':
      selected_item = get_object_or_404(Item, pk=request.POST.get('item_id'))
      # get the user you want (connect for example) in the var "user"
      user.item = selected_item
      user.save()

      # Then, do a redirect for example

   return render_to_response ('select/item.html', {'items':item}, context_instance =  RequestContext(request),)

Of course, don't forget to include get_object_or_404


Here is a more dry way to do this in 2021:

models.py

 from django.db import models

class Country(models.Model):
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name

class City(models.Model):
    country = models.ForeignKey(Country, on_delete=models.CASCADE)
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name

class Person(models.Model):
    name = models.CharField(max_length=100)
    birthdate = models.DateField(null=True, blank=True)
    country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True)
    city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True)

    def __str__(self):
        return self.name

urls.py

from django.urls import include, path

from . import views

urlpatterns = [
    path('', views.PersonListView.as_view(), name='person_changelist'),
    path('add/', views.PersonCreateView.as_view(), name='person_add'),
    path('<int:pk>/', views.PersonUpdateView.as_view(), name='person_change'),
]

views.py

from django.views.generic import ListView, CreateView, UpdateView
from django.urls import reverse_lazy
from .models import Person

class PersonListView(ListView):
    model = Person
    context_object_name = 'people'

class PersonCreateView(CreateView):
    model = Person
    fields = ('name', 'birthdate', 'country', 'city')
    success_url = reverse_lazy('person_changelist')

class PersonUpdateView(UpdateView):
    model = Person
    fields = ('name', 'birthdate', 'country', 'city')
    success_url = reverse_lazy('person_changelist')

HTML

{% extends 'base.html' %}

{% block content %}
  <h2>Person Form</h2>
  <form method="post" novalidate>
    {% csrf_token %}
    <table>
      {{ form.as_table }}
    </table>
    <button type="submit">Save</button>
    <a href="{% url 'person_changelist' %}">Nevermind</a>
  </form>
{% endblock %}

RESULT:

Django Dropdown populate from database

Reference: https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜