我遇到一个奇怪的问题,我似乎无法在 django 中的表单中设置其中一个字段的初始值。
我的模型字段是:
section = models.CharField(max_length=255, choices=(('Application', 'Application'),('Properly Made', 'Properly Made'), ('Changes Application', 'Changes Application'), ('Changes Approval', 'Changes Approval'), ('Changes Withdrawal', 'Changes Withdrawal'), ('Changes Extension', 'Changes Extension')))
我的表单代码是:
class FeeChargeForm(forms.ModelForm):
class Meta:
model = FeeCharge
# exclude = [] # uncomment this line and specify any field to exclude it from the form
def __init__(self, *args, **kwargs):
super(FeeChargeForm, self).__init__(*args, **kwargs)
self.fields['received_date'] = forms.DateField(('%d/%m/%Y',), widget=forms.DateTimeInput(format='%d/%m/%Y', attrs={'class': 'date'}))
self.fields['comments'].widget.attrs['class']='html'
self.fields['infrastructure_comments'].widget.attrs['class']='html'
我的查看代码是:
form = FeeChargeForm(request.POST or None)
form.fields['section'].initial = section
其中,section 是传递给函数的 url 变量。我试过了:
form.fields['section'].initial = [(section,section)]
也没有运气:(
任何想法我做错了什么,或者有没有更好的方法来从 url var 设置此选择字段的默认值(在表单提交之前)?
提前致谢!
Update:这似乎与 URL 变量有关。如果我使用:
form.fields['section'].initial = "Changes Approval"
它可以工作 np.. 如果我 HttpResponse(section) 它输出正确。