Brant Brant - 4 months ago 21
Python Question

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?

Answer

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.