1

My view:

form1 = UserProfile(request.POST or None, user=request.user)

My form:

class UserProfile(forms.Form):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop("user")
        super(UserProfile, self).__init__(*args, **kwargs)

    first_name = forms.CharField(max_length=30,required=True,widget=forms.TextInput(attrs={'placeholder': self.user.first_name }))
    last_name = forms.CharField(max_length=30,required=True,widget=forms.TextInput(attrs={'placeholder': self.user.last_name }))

NameError at /settings/ name 'self' is not defined Request Method: GET Request URL:

http://localhost:8000/settings/

Django Version: 1.5.2 Exception Type: NameError Exception Value: name 'self' is not defined

I tried to find solutions so far, and so far I came up with these codes then still in error.

James Aylett
  • 3,332
  • 19
  • 20
Jules Lee
  • 83
  • 2
  • 7
  • 1
    Could you post the entire stacktrace, please? – Henrik Andersson Sep 02 '13 at 18:59
  • what's a stacktrace? sorry, i'm still very new to stackoverflow. i just registered because of this one problem i cannot solve. I was just hoping to find a solution to my problem where I'd get to be able to make my placeholder display from what's inside the request.user object – Jules Lee Sep 02 '13 at 19:04
  • You need to indent the class code. – Miquel Sep 02 '13 at 19:04
  • I already did man but the error is coming from field definition. And it seems that it's already been answered down below. But thanks man! – Jules Lee Sep 02 '13 at 19:16

1 Answers1

0

You cannot use self in your form field definitions since self variable is only available in the methods.

Your fields are dynamic and depends on the user variable passed in the constructor. Define your dynamic fields in __init__.py there you have self.user:

class UserProfile(forms.Form):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop("user")
        super(UserProfile, self).__init__(*args, **kwargs)

        self.fields['first_name'] = forms.CharField(max_length=30,required=True,widget=forms.TextInput(attrs={'placeholder': self.user.first_name }))
        self.fields['last_name'] = forms.CharField(max_length=30,required=True,widget=forms.TextInput(attrs={'placeholder': self.user.last_name }))

Also see:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • thanks man! I'm sorry for asking this dumb question. Thanks for the help! – Jules Lee Sep 02 '13 at 19:09
  • I got the answer! self.fields['first_name'] = forms.CharField(max_length=30,required=True,widget=forms.TextInput(attrs={'placeholder': user.first_name })) – Jules Lee Sep 02 '13 at 19:32