Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Django Authentication Authentication LoginView

what's the point of the 'if form_class is None' in the 'form_valid' method ?

in the class LoginView, I can't understand why do we check if the form_class in none

    def get_form(self, form_class=None):
        if form_class is None:
            form_class=self.get_form_class()
        return form_class(self.request,**self.get_form_kwargs())

the whole class is:

class LoginView(generic.FormView):
    form_class = AuthenticationForm
    success_url = '/'
    template_name = "blog/post_form.html"

    def get_form(self, form_class=None):
        if form_class is None:
            form_class=self.get_form_class()
        return form_class(self.request,**self.get_form_kwargs())

    def form_valid(self, form):
        login(self.request,form.get_user())
        return super().form_valid(form)

why not just use something like:

    def get_form(self):
        return self.form_class(self.request,**self.get_form_kwargs())

because the form_class will always be AuthenticationForm or am I missing something? Why should form_class be passed as a parameter in the get_form method? I am really confused on this.

anyone?

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,454 Points

In the default mode, form_class would not be provided as an argument, thus the get_form_class would return AuthenticationForm. However, if one wanted to provide an alternative form, then it could be passed to the get_form method.

It looks like the code was borrowed from the FormMixin class get_form method.

get_form(form_class=None) β€” Instantiate an instance of form_class using get_form_kwargs(). If form_class isn’t provided get_form_class() will be used.

ForumMixin.get_form source code:

    def get_form(self, form_class=None):
        """Return an instance of the form to be used in this view."""
        if form_class is None:
            form_class = self.get_form_class()
        return form_class(**self.get_form_kwargs())