我遇到了一个奇怪的问题,我似乎无法在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节是传递给函数的url变量。我试过:
form.fields['section'].initial = [(section,section)]也没有运气:
有什么想法我做错了吗?还是有更好的方法从url var设置这个选择字段的默认值(在表单提交之前)?
提前感谢!
更新:似乎与变量有关。如果我用:
form.fields['section'].initial = "Changes Approval"它起作用了..。如果I HttpResponse(区段)输出正确,则输出正确。
发布于 2011-10-24 05:13:00
更新,尝试转义您的url。以下答案和文章应该是有帮助的:
How to percent-encode URL parameters in Python?
http://www.saltycrane.com/blog/2008/10/how-escape-percent-encode-url-python/
尝试将该字段的初始值设置如下,并查看该值是否有效:
form = FeeChargeForm(initial={'section': section})当用户发布表单时,我假设您将做很多其他事情,因此您可以使用如下方法将POST表单与标准表单分开:
if request.method == 'POST':
form = FeeChargeForm(request.POST)
form = FeeChargeForm(initial={'section': section})发布于 2014-01-29 12:33:49
问题是同时使用request.POST和initial={'section': section_instance.id})。这是因为request.POST的值总是覆盖参数initial的值,所以我们必须将它分开。我的解决办法就是用这种方式。
在views.py中:
if request.method == "POST":
form=FeeChargeForm(request.POST)
else:
form=FeeChargeForm() 在forms.py中:
class FeeChargeForm(ModelForm):
section_instance = ... #get instance desired from Model
name= ModelChoiceField(queryset=OtherModel.objects.all(), initial={'section': section_instance.id})在views.py中:
if request.method == "POST":
form=FeeChargeForm(request.POST)
else:
section_instance = ... #get instance desired from Model
form=FeeChargeForm(initial={'section': section_instance.id}) 在forms.py中:
class FeeChargeForm(ModelForm):
name= ModelChoiceField(queryset=OtherModel.objects.all())https://stackoverflow.com/questions/7871488
复制相似问题