因此,Django表单的 View 逻辑的标准模式为:
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,
})
在简单的情况下这很好,但是如果您的应用程序逻辑变得更加复杂,则很容易陷入大量嵌套的IF语句中。
任何人都可以分享他们自己的更干净的方法来避免嵌套IF和依赖于失败情况的逻辑吗?
我对不依赖于其他第三方应用程序的答案特别感兴趣。
最佳答案
包含的基于类的 View 之一是FormView
(documentation)。您需要关注的两个主要方法是form_valid
和form_invalid
。
from django.views.generic import FormView
from myapp.forms import MyForm
class MyView(FormView):
template_name = 'edit_something.html'
form_class = MyForm
success_url = '/success/' # you should use `reverse`, but let's stay focused.
def form_valid(self, form):
"""
This is what's called when the form is valid.
"""
return super(MyView, self).form_valid(form)
def form_invalid(self, form):
"""
This is what's called when the form is invalid.
"""
return self.render_to_response(self.get_context_data(form=form))
另外,您可以覆盖
post
,get
或put
方法,并根据每种请求类型处理表单。
关于django - Django表单逻辑的更好模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5871673/