django - Django表单逻辑的更好模式吗?

标签 django django-forms

因此,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_validform_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))

另外,您可以覆盖postgetput方法,并根据每种请求类型处理表单。

关于django - Django表单逻辑的更好模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5871673/

相关文章:

python - 反向未找到错误

python - 为什么我的 Django ModelForm 不会引发 unique_together 约束的验证错误?

django - --fake-initial与--fake在Django迁移中?

django 在干净的方法中更改表单数据

python - Django Userena 更改 url 监护人错误

除非经过检查,否则带有 BooleanField 的 Django 表单总是无效的

django - 如何使用地理位置 API 向用户位置提供默认点域值,无法将字符串转换为 float :

django - 如何将 ModelForm 与 django-address 一起使用?

python - 奇怪的 Django AuthenticationForm 行为

python - 将模型关系指定为字符串与具体模型?