在视图中处理表单的建议模式对我来说似乎过于复杂和非干:
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()构造,并且整个块在视图需要处理表单的任何地方重复.是不是有更好的方法呢?
当然,你可以避免重复.通常,您需要将要使用的表单和模板名称作为参数传入,在提交有效表单时处理已清理数据的可调用对象,以及在此类处理之后进行重定向的目标; 另外,您需要一些额外的代码来调用表单类一次,生成绑定或未绑定的表单,并正确处理它.即:
def process_any_form(request, form_class, template_file_name, process_data_callable, redirect_destination): form = form_class(request.POST if request.method == 'POST' else None) if form.is_bound and form.is_valid(): process_data_callable(form.cleaned_data) return HttpResponseRedirect(redirect_destination) return render_to_response(template_file_name, {'form': form})
你是对的它可能会更好,这是一个更好的选择(但继续阅读):
def contact(request): form = ContactForm(request.POST or None) # 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 return render_to_response('contact.html', { 'form': form, })
这个片段来自DjangoCon11的一个名为Advanced Django Form Usage的演讲.
请注意,如果所有字段都是可选字段且您不使用CSRF保护,则会将空表单处理为有效(即使在提交之前).所以为了消除这种风险,你最好使用这个:
def contact(request): form = ContactForm(request.POST or None) # A form bound to the POST data if request.method == 'POST' and form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data # ... return HttpResponseRedirect('/thanks/') # Redirect after POST return render_to_response('contact.html', { 'form': form, })