我已经创建了注册表。当我单击提交按钮时,form.is_valid()返回false。所以我的数据没有保存。 Django版本:1.4 以下是我的代码:
forms.py
class RegisterForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
self.fields['user_type'].required = True
class Meta:
model=RegisterModel
的index.html
<form action="/registration/" method="POST">
<table border="0" cellspacing="8" align="center">
<tr>
{{form.user_type.errors}}
<td> User Type:</td>
<td style="text-align:left !important">{{ form.user_type }}</td>
</tr>
<tr>
{{form.pricing_plan.errors}}
<td class="align-left" width="85">Pricing Plan:</td>
<td width="190" style="text-align:left !important">{{ form.pricing_plan }}</td>
</tr>
<tr>
{{form.full_name.errors}}
<td class="align-left">Full Name:</td>
<td>{{ form.full_name }}</td>
</tr>
<div class="submit-reset">
<input type="submit" value="Submit" id="button" class="sub-res-btn"/> <input type="Reset" id="button" class="sub-res-btn"/>
</div>
</form>
views.py
def user_registration(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
print "form is valid or not", form.is_valid()
if form.is_valid():
form.save()
return HttpResponseRedirect('/marketing/')
extra_context = {}
extra_context['form'] = RegisterForm()
return render_to_response('index.html', extra_context, context_instance=RequestContext(request))
答案 0 :(得分:2)
当您收到无效表单时,请勿重置表单,并在模板中显示{{form.non_field_errors}}
。
您可以将视图代码更新为:
def user_registration(request):
extra_context = {}
if request.method == 'POST':
form = RegisterForm(request.POST)
print "form is valid or not", form.is_valid()
if form.is_valid():
form.save()
return HttpResponseRedirect('/marketing/')
else:
form = RegisterForm()
extra_context['form'] = form
return render_to_response('index.html', extra_context,
context_instance=RequestContext(request))