1

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?

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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'

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.