I am trying to build custom django form for changing username and user email for an application. That’s why I need to pass the user details from the session to a form in order to check if the logged user exists. I am doing in this way:
in views.py
personal_info_form = PersonalInfoForm(prefix='personal_info',
user_details=user_details)
where user_details is a dictionary:
'user_details': [{'username': u'username',
'registration_date': datetime.date(2009, 10, 22),
'id': 13, 'email': u'user@mail.com'}]}
In forms.py I have the following code:
class PersonalInfoForm(forms.Form):
def __init__(self, *args, **kwargs):
user_details = kwargs.pop('user_details', None)
super(PersonalInfoForm, self).__init__( *args, **kwargs)
username = forms.CharField(required=True, initial=user_details[0]['username'])
email = forms.EmailField(required=True)
And I get the following error:
name 'user_details' is not defined
I tried accessing it with self.user_details and only user_details and it gives me the same error
user_detailsis passed to__init__, so is not defined outside of it. That’s why you can’t access it when you’re instatiating that CharField object. Setinitialin__init__itself, after you’ve popped it from kwargs, for instance:When you get a chance, consider reading up on scopes in python.