Using UserCreationForm

I am learning django. I would like to understand below code.

class RegisterPage(FormView):
    template_name = 'base/register.html'
    form_class = UserCreationForm
    redirect_authenticated_user = True
    success_url = reverse_lazy('tasks')

    def form_valid( self, form ):
        user = form.save()
        if user is not None:
            login( self.request, user )
        return super( RegisterPage, self ).form_valid( form )
    
    def get( self, *args, **kwargs ):
        if self.request.user.is_authenticated:
            return redirect('tasks')
        return super(RegisterPage, self).get(*args, **kwargs)

Can I use def register( self, form ): instead of def form_valid( self, form ): ?

How self and form are passing here ?

Can I use def save( self, *args, **kwargs ): instead of def get( self, *args, **kwargs ): ?

Hello there!
You’re using a class-based-view also called CBV, CBVs give you methods and attributes that you can override to write less code, but sometimes if you find yourself overriding a lot of methods to get the behavior you want it would be better to not use a CBV (it’s not the case here).

No, you can’t. Because form_valid is being called by the FormView.

This is being bassed by FormView.

Also can’t. The method get (and also others that have the http method name) have a special meaning, they handle a request for that http method.

If you wish, you can dive into the source code to better understand what’s going on.

Here’s the source code for the FormView.
If you pay attention, FormView inherits from 2 classes, but let’s concentrate on: BaseFormView that’s defined just above the FormView class. And BaseFormView also inherits from other 2 classes, i believe the most important one to note is the ProcessFormView there you can figure it out how that the arguments are passed to the function, and why the form_valid method needs to be named like that.

Hope this helps you find the answers you’re looking for.
Also a great resource about CBVs is this: https://ccbv.co.uk/

1 Like

@leandrodesouzadev Thanks. Your information is effective. Thanks.

@leandrodesouzadev , Could you please explain this line return super( RegisterPage, self ).form_valid( form ) ?

It’s calling the super method form_valid, on your class hierarchy this would be FormView, that itself would be this specific method

Thanks @leandrodesouzadev . Could you please say what is the difference between these twos ?

return super( RegisterPage, self ).form_valid( form )
return super().form_valid(form)

Thanks.

Well, this question is out of the scope of the Django scenario.
But you’ll like to know that this information is available on the first paragraphs of the python’s documentation about the super built-in function

1 Like

Thanks @leandrodesouzadev . But I couldn’t clear after reading documentation.

Could you please explain a little ?

Thanks.