Render a template instead a success_url in form_va

2019-06-21 20:38发布

问题:

As the title says: I need to render a template after submitting a form, this form is handled with FormView with the method form_valid. With the method post, I can render a template after submitting it but maybe with form_valid, I can do it in the cleanest way.

How can I do it?

回答1:

The default implementation of form_valid is to redirect to success_url, you only need to override it to render some page. Here is the example.

class ChangePasswordPage(FormView):
    template_name = 'core/password-change.html'
    form_class = PasswordChangeForm

    def form_valid(self, form):
        form.save()
        messages.success(self.request, "Your password is changed")
        return render(self.request, 'core/password-change-success.html', self.get_context_data())