10

I am calling a form as follows, then passing it to a template:

f = UserProfileConfig(request)

I need to be able to access the request.session within the form... so first I tried this:

class UserProfileConfig(forms.Form):

    def __init__(self,request,*args,**kwargs):
        super (UserProfileConfig,self).__init__(*args,**kwargs)
        self.tester = request.session['some_var']

    username = forms.CharField(label='Username',max_length=100,initial=self.tester)

This didn't work, I gather, because of when the form is constructed compared to setting the username charfield.

So, next I tried this:

class UserProfileConfig(forms.Form):

def __init__(self,request,*args,**kwargs):
    super (UserProfileConfig,self).__init__(*args,**kwargs)
    self.a_try = forms.CharField(label='Username',max_length=100,initial=request.session['some_var'])


username = self.a_try

To no avail.

Any other ideas?

Brant
  • 5,721
  • 4
  • 36
  • 39

3 Answers3

15

Try this:

class UserProfileConfig(forms.Form):

    def __init__(self,request,*args,**kwargs):
        super (UserProfileConfig,self).__init__(*args,**kwargs)
        self.fields['username'] = forms.CharField(label='Username',max_length=100,initial=request.session['some_var'])

I find this article about dynamic forms very helpful.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Worked like a charm! Thanks so much. Been wrestling this one for a while. – Brant Mar 03 '10 at 18:57
  • @Felix- What would be a simple Form for it? I am saving a ```List``` in the session that contains the ```CheckBoxSelectMultiple```. I'll put the link here. Please have a look. Much appreciated. – Deshwal Sep 06 '19 at 19:48
  • can you please take a loot at [this](https://stackoverflow.com/questions/57830992/error-while-accessing-request-sessionkey-inside-forms-using-checkboxselect) – Deshwal Sep 07 '19 at 05:40
1

I am so surprised that Django use session in form is so hard. sometimes we really need use session data in form to valid fields.

I create a small project can solve this. django-account-helper

example code:

from account_helper.middleware import get_current_session

Class YourForm(forms.Form):

    def clean(self):
        session = get_current_session()
        if self.cleaned_data.get('foo') == session.get('foo'):
            # do something
            pass

        #... your code
    pass
9nix00
  • 3,852
  • 2
  • 21
  • 27
0

#iN VIEW

    form = MyForm(request.POST, request=request)

#in FORM

self.request = kwargs.pop('request', None)
if self.request:
    my_variable_value = self.request.session.get('VARIABLE_NAME')
    print("APPLICATION_ID",my_variable_value)
else:
   print("Not found",self.request)