[Django]-Django: How to provide context into a FormView get() method (also using request param)

9👍

Ditch the request argument to the get_context_data method. You should also use the dispatch method to check if the user is logged in.

class LoginView(FormView):
    template_name = 'members/login.html'
    form_class = LoginForm

    def dispatch(self, *args, **kwargs):
        """Use this to check for 'user'."""
        if request.session.get('user'):
            return redirect('/dashboard/')
        return super(LoginView, self).dispatch(*args, **kwargs)

    def get_context_data(self, **kwargs):
        """Use this to add extra context."""
        context = super(LoginView, self).get_context_data(**kwargs)
        context['message'] = self.request.session['message']
        return context

Leave a comment