我遇到了一个奇怪的问题,我似乎无法在 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'
我的 View 代码是:
form = FeeChargeForm(request.POST or None)
form.fields['section'].initial = section
其中 section 是传递给函数的 url 变量。我试过:
form.fields['section'].initial = [(section,section)]
也没有运气:(
知道我做错了什么,或者是否有更好的方法从 url var 设置此选择字段的默认值(在表单提交之前)?
提前致谢!
更新:这似乎与 URL 变量有关。如果我使用:
form.fields['section'].initial = "Changes Approval"
它工作 np.. 如果我 HttpResponse(section) 它输出正确。
最佳答案
问题是一起使用 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())
关于python - choicefield的Django初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7871488/