问题
When I am rendering my form django always shows an error message on each field "This field is required" even though the form is not submitted. What could be the problem?
Here is my model form
class MMEditidStateForm(forms.ModelForm):
class Meta:
model = models.MMEditidState
exclude = ('status_id',)
Here is my model
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)
Here is my view
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))
Now I am just rendering my form in the template as
<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>
Please let me know what could be the problem? Previously I didn't got this error message
回答1:
Because you're always instantiating your form with request.POST, even when you're not actually posting to it. In your else clause, drop the request.POST.
回答2:
or use
form = forms.MMEditidStateForm(request.POST or None)
without if condition, like this:
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))
回答3:
For those who still seek the answer: I had the same problem. In this case, my recommendation is to update this line:
form = forms.MMEditidStateForm(request.POST or None)
hope it helps.
来源:https://stackoverflow.com/questions/5806059/django-form-always-shows-error-this-field-is-required