在django中,提供了表单类来简化这个过程。 What you want is to create a form class with a ChoiceField. You can grab the data in this form rather than the views.py and then create a tuple the choices available from your dataset. We will do this by overriding the form's init field so that load a dynamic set of choices instead of static set of choices. 示例:
from django import forms
from yourapp.models import Brand
class BrandForm(forms.Form):
def __init__(self, *args, **kwargs):
super(BrandForm, self).__init__(*args, **kwargs)
brands = Brand.objects.all()
brand_choices = tuple(i, brand.brand_name for i, brand in enumerate(brands))
self.fields['brand'] = forms.ChoiceField(choices=brand_choices)
Now in views.py you need to initialize the form and pass it into the context when you call render() 然后,只需将{{ form }}放入html表单,将所有字段加载到表单中 (if您没有将窗体作为"form"传递到上下文中,您将需要更改{{ }}内部的引用) 附言:使用一组静态的选择,可以在类之外定义元组,并像这样定义类(不需要覆盖__init__):
class BrandForm(forms.Form):
brand = forms.ChoiceField(choices=choices)
1条答案
按热度按时间wnavrhmk1#
在django中,提供了表单类来简化这个过程。
What you want is to create a form class with a ChoiceField. You can grab the data in this form rather than the views.py and then create a tuple the choices available from your dataset. We will do this by overriding the form's init field so that load a dynamic set of choices instead of static set of choices.
示例:
Now in views.py you need to initialize the form and pass it into the context when you call
render()
然后,只需将
{{ form }}
放入html表单,将所有字段加载到表单中(if您没有将窗体作为"form"传递到上下文中,您将需要更改
{{ }}
内部的引用)附言:使用一组静态的选择,可以在类之外定义元组,并像这样定义类(不需要覆盖__init__):
更多例子可以在django文档中找到:https://docs.djangoproject.com/en/4.1/topics/forms/