views:

180

answers:

3

Why can't I do this?

from django import forms
from django.forms import widgets
class UserProfileConfig(forms.Form):

    def __init__(self,*args,**kwargs):
        super (UserProfileConfig,self).__init__(*args,**kwargs)
        self.tester = 'asdf'

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

More specifically, why cant the forms.CharField grab the variable tester that I set during construction?

I feel like I am missing something about the way Python handles this sort of thing...

edit :

What I am actually trying to do is 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)

In other words, I need to grab a session variable and then set it to an initial value...

Is there any way to handle this through the __init__ or otherwise?

+1  A: 

You can just do it this way

from django import forms
from django.forms import widgets
class UserProfileConfig(forms.Form):
    username = forms.CharField(label='Username',max_length=100,initial=self.tester)
    tester = 'asdf'
voyager
+2  A: 

What you've got doesn't work because your CharField gets created, and pointed to by UserProfileConfig.username when the class is created, not when the instance is created. self.tester doesn't exist until you call __init__ at instance creation time.

jcdyer
A: 

You could do this:-

class UserProfileConfig(forms.Form):

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


def view(request):
    user_form = UserProfileConfig(initial={'username': request.session['username',})

Which is the generally accepted method, but you can also do this:-

class UserProfileConfig(forms.Form):

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


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


def view(request):
    user_form = UserProfileConfig(request=request)
davetdog