views:

272

answers:

1

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?

+1  A: 

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
Worked like a charm!Thanks so much. Been wrestling this one for a while.
Brant