如何在“选择”窗口小部件中使用模型对象构建Django窗体? [英] How do I construct a Django form with model objects in a Select widget?
问题描述
类网站(models.Model):
name = models.CharField(max_length = 50)
我的网站值是(key,value):
1。 Stackoverflow
2. Serverfault
3.超级用户
我想构建一个表单使用具有上述值的html选择小部件:
< select>
< option value =1> Stackoverflow< / option>
< option value =2> Serverfault< / option>
< option value =3>超级用户< / option>
< / select>
我正在考虑从以下代码开始,但不完整:
class SiteForm(forms.Form):
site = forms.IntegerField(widget = forms.Select())
任何想法,我可以用Django表单实现吗?
编辑
不同的页面将呈现不同的网站值。开发者页面将显示开发网站,而烹饪页面将显示食谱网站。我基本上是想根据视图动态填充小部件选择。我相信我现在可以通过在模板中手动生成html来实现。
我想你在找 ModelChoiceField
。
更新:特别注意 queryset
参数。在支持该页面的视图中,您可以根据您关心的任何条件更改您提供的 QuerySet
。
Let's say I'm using the Django Site model:
class Site(models.Model):
name = models.CharField(max_length=50)
My Site values are (key, value):
1. Stackoverflow
2. Serverfault
3. Superuser
I want to construct a form with an html select widget with the above values:
<select>
<option value="1">Stackoverflow</option>
<option value="2">Serverfault</option>
<option value="3">Superuser</option>
</select>
I'm thinking of starting with the following code but it's incomplete:
class SiteForm(forms.Form):
site = forms.IntegerField(widget=forms.Select())
Any ideas how I can achieve that with Django form?
EDIT
Different pages will present different site values. A dev page will show development sites while a cooking page will show recipe sites. I basically want to dynamically populate the widget choices based on the view. I believe I can achieve that at the moment by manually generating the html in the template.
I think you're looking for ModelChoiceField
.
UPDATE: Especially note the queryset
argument. In the view that is backing the page, you can change the QuerySet
you provide based on whatever criteria you care about.
这篇关于如何在“选择”窗口小部件中使用模型对象构建Django窗体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!