我遇到了一个奇怪的问题,我似乎无法在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变量设置这个选项字段的默认值(在表单提交之前)?
提前谢谢!
更新:这似乎与URL变量有关。。如果我使用:
form.fields['section'].initial = "Changes Approval"
它是np.的。。如果我的HttpResponse(部分)它的输出正确。
问题是一起使用
request.POST
和initial={'section': section_instance.id})
。这是因为request.POST
的值总是覆盖参数initial
的值,所以必须将其分开。我的解决办法是用这种方式。在views.py中:
在forms.py中:
—————————————————————————
在views.py中:
在forms.py中:
更新 尝试转义您的url。下面的答案和文章应该会有帮助:
How to percent-encode URL parameters in Python?
http://www.saltycrane.com/blog/2008/10/how-escape-percent-encode-url-python/
尝试按以下方式设置该字段的初始值,并查看是否有效:
我假设当用户发布表单时,您会做很多其他事情,这样您就可以使用以下内容将POST表单与标准表单分开:
相关问题 更多 >
编程相关推荐