form_Valid 函数在 django 中如何工作?

Ton*_*ana 5 python django django-models django-forms django-views

返回行上的这个表单对象是什么,是提交表单收到的表单对象吗?。因为我们用 return super().form_valid(form) 返回它。可以像上下文变量一样访问它吗?从 success_url 表示的模板中。另外 form_valid 指向 success_url ,因为我们正在执行 super() ,所以它不应该指向父类的 success_url 。但为什么它会转到ContactView的success_url。

class ContactView(FormView):
    template_name = 'contact.html'
    form_class = ContactForm
    success_url = '/thanks/'

    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.
        # It should return an HttpResponse.
        form.send_email()
        return super().form_valid(form)
Run Code Online (Sandbox Code Playgroud)

Wil*_*sem 5

form返回线上的这个对象是什么?

formContactFormDjango 构建的用于验证 POST 请求的实例。例如,您可以通过以下方式从表单中获取清理后的数据:

class ContactView(FormView):
    template_name = 'contact.html'
    form_class = ContactForm
    success_url = '/thanks/'

    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.
        # It should return an HttpResponse.
        form.send_email()
        print(form.cleaned_data)
        return super().form_valid(form)
Run Code Online (Sandbox Code Playgroud)

因此,将用and和 checkFormView构造一个。如果是,它将使用此表单实例进行调用。ContactFormrequest.POSTrequest.FILESform.is_valid()form_valid

既然我们这样做了super(),它不应该指向父类的 success_url 吗?

super()是一个代理对象,它将向上移动 MRO 并因此调用父方法,但该父方法实现为 [GitHub]

    def form_valid(self, form):
        """If the form is valid, redirect to the supplied URL."""
        return HttpResponseRedirect(self.get_success_url())
Run Code Online (Sandbox Code Playgroud)

self然而该对象仍然是一个ContactView对象,因此self.get_success_url()将返回success_url.

然而,经常使用reverse_lazy[Django-doc] 。这样你就可以提供视图的名称,Django 可以自动计算 URL:

from django.urls import reverse_lazy

class ContactView(FormView):
    template_name = 'contact.html'
    form_class = ContactForm
    success_url = reverse_lazy('name-of-thanks-view')
Run Code Online (Sandbox Code Playgroud)