Django View出错时返回self

时间:2016-05-26 08:21:10

标签: django

处理看似简单的Django视图,但不断出现错误。

class RegistrationView(View):
    def get(self, request, *args, **kwargs):
        context = {
            "user_form": UserForm(),
            "contact_form": ContactForm(),
            "company_form": CompanyForm(),
        }

        return render(request, "accounts/registration_form.html", context)

    def post(self, request, *args, **kwargs):
        user_form = UserForm(request.POST)
        contact_form = ContactForm(request.POST)
        company_form = CompanyForm(request.POST)

        if user_form.is_valid() and contact_form.is_valid() and company_form.is_valid():
            self.form_valid()
        else:
            self.form_invalid(user_form, contact_form, company_form)

    def form_valid(self):
        return HttpResponseRedirect("/accounts/registration-complete")

    def form_invalid(self, user_form, contact_form, company_form):
        context = {
            "user_form": user_form,
            "contact_form": contact_form,
            "company_form": company_form
        }

        return render_to_response(self.request, "accounts/registration_form.html", context)

当我在is_valid()上查看user_form,contact_form和company_form时,我发现company_form无效,因此我转到form_invalid()方法。
在这里,我应该被重定向到相同的视图,预先填充数据,并在屏幕上显示一些错误。

现在我收到错误TemplateDoesNotExist at /accounts/register/
当我更换

return render_to_response(self.request, "accounts/registration_form.html", context)

return render(self.request, "accounts/registration_form.html", context)

我收到另一条错误消息:

ValueError at /accounts/register/
The view accounts.views.RegistrationView didn't return an HttpResponse object.

这很有道理,但我不确定如何解决这个问题。 我希望有一个简单的解决方案。

2 个答案:

答案 0 :(得分:2)

post方法中,您实际需要return调用form_validform_invalid的结果:

    if user_form.is_valid() and contact_form.is_valid() and company_form.is_valid():
        return self.form_valid()
    else:
        return self.form_invalid(user_form, contact_form, company_form)

否则您的post方法根本不会返回任何内容!

答案 1 :(得分:1)

问题不是你在呼叫render; 返回HttpResponse。问题是您的post方法未返回调用form_valid()(或无效)的值。

if user_form.is_valid() and contact_form.is_valid() and company_form.is_valid():
    return self.form_valid()
else:
    return self.form_invalid(user_form, contact_form, company_form)