Django: How to access session data from inside a FormView in forms.py


1. Add get_form_kwargs() to your FormView in views.py:
class RegistrationFormView(FormView):
    template_name = 'registration/registration_form.html'
    form_class = RegistrationForm
    success_url = 'results'
 
    def get_form_kwargs(self):
        kwargs = super(RegistrationFormView, self).get_form_kwargs()
        kwargs.update({
            'request': self.request
        })
        return kwargs
2. Change __init__ in your forms.py to include request as a parameter:
def __init__(self, request, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)
3. Access your session data:
print(request.session['first_name'])
© 2011 Adam Gerson.