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
user_details
is 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. Set initial
in __init__
itself, after you've popped it from kwargs, for instance:
class PersonalInfoForm(forms.Form):
username = forms.CharField(required=True)
email = forms.EmailField(required=True)
def __init__(self, *args, **kwargs):
user_details = kwargs.pop('user_details', None)
super(PersonalInfoForm, self).__init__(*args, **kwargs)
if user_details:
self.fields['username'].initial = user_details[0]['username']
When you get a chance, consider reading up on scopes in python.