[Django]-Passing **kwargs to Django Form

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.

👤ozan

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.

👤Clash

Leave a comment