[Django]-How can I get session in forms?

5👍

As you have found, you can’t access request inside the form definition.

You can override the __init__ method to take extra parameters, and set the queryset for your field. In the example below, I’ve used session_icons as the argument, instead of request.

class IconSubChoiceForm(forms.ModelForm):
    icons = CustomSubChoiceField(queryset=CanvaIcon.objects.none(), widget=forms.CheckboxSelectMultiple)

    def __init__(self, *args, **kwargs):
        session_icons = kwargs.pop('session_icons')
        super(IconSubChoiceForm, self).__init__(*args, **kwargs)
        self.fields['icons'].queryset = CanvaIcon.objects.filter(...)

Then in your view, instantiate your form with session_icons.

form = IconSubChoiceForm(data=request.POST, session_icons=request.session.get('icons'))

Leave a comment