3

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 ?

Horai Nuri
  • 5,358
  • 16
  • 75
  • 127
  • Can you share the code. I have the same requirement but when I processthe form using ```form =FormName(request.post)``` it throws exception saying ```Queryset has no attribute session``` – Deshwal Sep 06 '19 at 19:26
  • Plus am using the ```request.session['key']=[]``` and ```MultipleChoiceFieldForm``` – Deshwal Sep 06 '19 at 19:27
  • can You help me out [with this one](https://stackoverflow.com/questions/57830992/error-while-accessing-request-sessionkey-inside-forms-using-checkboxselect) ? – Deshwal Sep 07 '19 at 05:59

1 Answers1

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'))
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • Alright, I tried it but it is giving me this error `TypeError: __init__() missing 1 required positional argument: 'queryset'`, CustomSubChoiceField is asking a queryset argument, what should I put in it ? – Horai Nuri Mar 08 '17 at 13:45
  • You can use the empty queryset `queryset=CanvaIcon.objects.none()`, since you are going to replace it in the `__init__` method. – Alasdair Mar 08 '17 at 13:52