我无法在加载表单时为下拉列表设置默认值。
这是代码
state = forms.TypedChoiceField(choices = formfields.State)
State = (
('QC_APPROVED','QC_APPROVED'),
('REVERT','REVERT'),
('FIXED','FIXED'),
)
如果我想将默认状态设为FIXED。我正在写这段代码
state = forms.TypedChoiceField(choices = formfields.State, default = 'FIXED')
如果我执行上面的代码,我收到以下错误。
Exception Value: __init__() got an unexpected keyword argument 'default'
有人可以为此提供帮助吗?
答案 0 :(得分:18)
state = forms.TypedChoiceField(choices=formfields.State, initial='FIXED')
如文档中所示:http://docs.djangoproject.com/en/dev/ref/forms/fields/#initial
答案 1 :(得分:2)
字段采用initial
值
答案 2 :(得分:1)
我在寻找如何为外键字段设置Django表单的初始“选定”状态时遇到了这个线程,所以我只想补充一下,您可以按照以下步骤进行操作:
models.py:
class Thread(NamedModel):
topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
title = models.CharField(max_length=70, blank=False)
forms.py:
class ThreadForm(forms.ModelForm):
class Meta:
model = Thread
fields = ['topic', 'title']
views.py:
def createThread(request, topic_title):
topic = Topic.getTopic(topic_title)
threadForm = ThreadForm(initial={'topic': topic.id})
...
关键是设置initial={'topic': topic.id}
,我认为这没有充分记录。
答案 3 :(得分:0)
state = forms.TypedChoiceField(choices=formfields.State, initial='FIXED')
title = forms.CharField(widget=forms.Select(choices=formfields.State) , initial='FIXED')
toppings = forms.ChoiceField(
widget=forms.Select(attrs={'class':"hhhhhhhh"}),
choices = formfields.State,
initial='FIXED'
)
答案 4 :(得分:-2)
尝试编号:
state = forms.TypedChoiceField(choices = formfields.State,default = 2)