在视图中处理表单的建议模式对我来说似乎过于复杂和非 DRY:
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render_to_response('contact.html', {
'form': form,
})
这是很多条件,它重复了 ContactForm() 构造,并且在视图需要处理表单的任何地方都重复了整个块。难道没有更好的方法吗?