How to process a form (via get or post) using class-based views?

The default behaviour of the FormView class is to display an unbound form for GET requests, and bind the form for POST (or PUT) requests. If the bound form is valid, then the form_valid method is called, which simply redirects to the success url (defined by the success_url attribute or the get_success_url method.

This matches the example quite well. You need to override the form_valid method to create the new User, before calling the superclass method to redirect to the success url.

class CreateUser(FormView):
    template_name="registration/register.html"
    success_url="/accounts/register/success/"
    form_class = RegistrationForm

    def form_valid(self, form):
        user = User.objects.create_user(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password1'],
                email=form.cleaned_data['email']
        )
        return super(CreateUser, self).form_valid(form)

Your first example does not match the flow of FormView so well, because you aren’t processing a form with POST data, and you don’t do anything when the form is valid.

I might try extending TemplateView, and putting all the logic in get_context_data.
Once you get that working, you could factor the code that parses the GET data and returns the bookmarks into its own method. You could look at extending ListView, but I don’t think there’s any real advantage unless you want to paginate results.

Leave a Comment

tech