我有一个奇怪的问题,我似乎无法设置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 var . 我试过了:
form.fields['section'].initial = [(section,section)]
没有运气:(
任何想法我做错了或者是否有更好的方法从url var设置此选择字段的默认值(在表单提交之前)?
提前致谢!
Update: 这似乎与URL变量有关..如果我使用:
form.fields['section'].initial = "Changes Approval"
它工作np ..如果我HttpResponse(部分)它输出正确tho .
2 回答
更新尝试转义您的网址 . 以下SO答案和文章应该有所帮助:
How to percent-encode URL parameters in Python?
http://www.saltycrane.com/blog/2008/10/how-escape-percent-encode-url-python/
尝试设置该字段的初始值,如下所示,看看是否有效:
我假设当用户发布表单时你会做很多其他的事情,所以你可以使用以下内容将POST表单与标准表单分开:
问题是使用request.POST和initial = {'section':section_instance.id}) . 发生这种情况是因为request.POST的值总是覆盖参数“initial”的值,所以我们必须将它分开 . 我的解决方案是使用这种方式 .
在views.py中:
在forms.py中:
在views.py中:
在forms.py中: