当我渲染表单时,django总是在每个字段上显示错误消息“此字段是必需的” 即使表单未提交。可能是什么问题?
这是我的模型表格
class MMEditidStateForm(forms.ModelForm):
class Meta:
model = models.MMEditidState
exclude = ('status_id',)
这是我的模特
class MMEditidState(models.Model):
state_id = models.IntegerField(primary_key = True)
state_dremelid = models.ForeignKey(MMDremelDump, db_column = 'state_dremelid')
assignee = models.CharField(max_length = 50)
state = models.CharField(max_length = 50)
role = models.CharField(max_length = 50)
date = models.DateTimeField()
class Meta:
db_table = u'mm_editid_state'
def __unicode__(self):
return u'%s %s' % (self.state_dremelid, self.assignee)
这是我的观点
def qcthisedit(request, get_id):
dremel_id = MMEditidState.objects.filter(pk=get_id).values('state_dremelid')
if request.method == "POST":
form = forms.MMEditidStateForm(request.POST)
if form.is_valid():
form.save()
return http.HttpResponseRedirect('/mmqc/dremel_list/')
else:
form = forms.MMEditidStateForm(request.POST)
return shortcuts.render_to_response('qcthisedit.html',locals(),
context_instance = context.RequestContext(request))
现在我只是在模板中将表单呈现为
<table>
<h3>Submit this form if there are no errors</h3>
<form action="." method="post">
{{form.as_table}}
</table>
<input type="submit" value="Submit">
<INPUT TYPE="BUTTON" VALUE="Go Back" ONCLICK="history.go(-1)"></form><br>
请让我知道可能是什么问题?以前我没有收到此错误消息
答案 0 :(得分:15)
因为您总是使用request.POST
实例化您的表单,即使您实际上没有发布它。在else
子句中,删除request.POST
。
答案 1 :(得分:3)
或使用
form = forms.MMEditidStateForm(request.POST or None)
没有条件,如下:
def qcthisedit(request, get_id):
dremel_id = MMEditidState.objects.filter(pk=get_id).values('state_dremelid')
form = forms.MMEditidStateForm(request.POST or None)
if form.is_valid():
form.save()
return http.HttpResponseRedirect('/mmqc/dremel_list/')
return shortcuts.render_to_response('qcthisedit.html',locals(),
context_instance = context.RequestContext(request))
答案 2 :(得分:0)
对于仍然寻求答案的人: 我有同样的问题。在这种情况下,我的建议是更新这一行:
form = forms.MMEditidStateForm(request.POST or None)
希望它有所帮助。