Django Dropdown从数据库填充

时间:2011-05-19 17:49:10

标签: django django-templates django-views

如果我通过视图将项目传递给模板,并且我希望用户选择一个提交给用户记录的值,我只能在模板中使用for循环吗?

那会是什么样子? 在模板中:

<form method="POST" 
<select>

</select>
</form>

型号:

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)

查看:

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)
               )

2 个答案:

答案 0 :(得分:22)

如果我理解你的需要,你可以这样做:

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

顺便说一下,你应该给出名称而不是item,因为它是一个集合(但它只是一个评论;))。

这样做,您将获得数据库中所有项目的列表。

然后,在帖子中,您需要做什么:

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),)

当然,不要忘记包含get_object_or_404

答案 1 :(得分:0)

这是在 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 %}

结果:

enter image description here

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