Django,ModelChoiceField()和初始值 [英] Django, ModelChoiceField() and initial value
本文介绍了Django,ModelChoiceField()和初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用这样的东西:
field1 = forms.ModelChoiceField(queryset=...)
如何使我的表单显示一个选定的值?
How can I make my form show the a value as selected?
推荐答案
如果要设置默认的初始值,您应该定义 initial
com / django-users@googlegroups.com/msg36019.htmlrel =noreferrer>将其设置为id 。
If you want to set the default initial value you should be defining initial
like other form fields except you set it to the id instead.
说你得到 field1
如下:
class YourForm(forms.Form):
field1 = forms.ModelChoiceField(queryset = MyModel.objects.all() )
然后您需要在创建表单时设置初始化:
then you need to set initial when you create your form like this:
form = YourForm(initial = {'field1': instance_of_mymodel.pk })
而不是:
form = YourForm(initial = {'field1': instance_of_mymodel })
我也假设你定义了 __unicode __
为您的型号,以便正确显示。
I'm also assuming you've defined __unicode__
for your models so this displays correctly.
这篇关于Django,ModelChoiceField()和初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文