Brant
Brant

Reputation: 6031

Django - Access request.session in form

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?

Upvotes: 10

Views: 13926

Answers (3)

Krishna Prasad
Krishna Prasad

Reputation: 34

#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)

Upvotes: 0

9nix00
9nix00

Reputation: 4082

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

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 817000

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.

Upvotes: 15

Related Questions