Search code examples
pythondjangodjango-formsdjango-sessions

How can I get session in forms?


I have a multistep form with checkboxes, after the user submit the first step form I save the objects he checked on his session, at the second step form I would like to filter the objects with the session datas.

To accomplish this I need to get the session on the new ModelForm for the second step, unfortunaltely request is not defined in forms.

How can I access my sessions ?

class IconSubChoiceForm(forms.ModelForm):
    session_icons = request.session.get('icons')
    query = Q(tags__contains=session_icons[0]) | Q(tags__contains=session_icons[1]) | Q(tags__contains=session_icons[2])
    icons = CustomSubChoiceField(queryset=CanvaIcon.objects.filter(query), widget=forms.CheckboxSelectMultiple)

    class Meta:
        model = CanvaIcon
        fields = ['icons']

Any suggestion ?


Solution

  • 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'))