36

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'[email protected]'}]}

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

2 Answers 2

52

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.

1
  • 2
    +1 beautiful. 10 seconds before submitting my very similar solution, the orange banner pops up...nicely done!
    – czarchaic
    Commented Jan 2, 2010 at 22:25
3

Can you explain in a more clear way what you are trying to do? I believe what you are doing is unnecessary. Not sure if I understood you, but take a look at Django Model Forms: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/

>>> from django.forms import ModelForm

# Create the form class.
>>> class ArticleForm(ModelForm):
...     class Meta:
...         model = Article

# Creating a form to add an article.
>>> form = ArticleForm()

# Creating a form to change an existing article.
>>> article = Article.objects.get(pk=1)
>>> form = ArticleForm(instance=article)

If it's what you are looking for, you could easily addapt to use your user model. Remember, you can pick which fields you want to allow to be changed. The instance parameter sets the initial field values (which is what I understood you want to do). The example above will show all fields, the below example shows how to display only 2 fields.

class PartialAuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title')

Hope I've helped.

2
  • I am trying to access variables from **kwargs in the Forms class. Commented Jan 2, 2010 at 22:13
  • Yes. It gives me name 'kwargs' is not defined Commented Jan 2, 2010 at 22:17

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.