Jason G
Jason G

Reputation: 200

How do I repopulate user info in a Django form?

Previsouly, I used forms.ModelForm to create a Django form and in views.py used:

p_form = ProfileUpdateForm(request.POST,
                                   request.FILES,
                                  instance=request.user.profile)

This way, if the form was not valid when submitted, it would repopulate the information the user entered previously. This saved a user from having to enter the information again.

I have since changed to forms.Form because I can't figure out how to customize Crispy Forms using forms.ModelForm, but now if I call instance=request.user.profile, I get an error.

What can I do to repopulate the information the user previously placed in the form so they do not have to do it again?

Upvotes: 1

Views: 134

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476584

You can populate the fields of a form with the initial=… parameter [Django-doc], this then contains a dictionary that maps the fields to the corresponding value.

So if your form for example is defined as:

class ProfileUpdateForm(forms.Form):
    name = forms.CharField()
    age = forms.IntegerField()

you can construct a form with:

ProfileUpdateForm(initial={'name': 'Jason G', 'age': 25})

A ModelForm basically does the same, except that here it obtains the initial values form the instance=… parameter, and thus obtains attributes from that object and passes these to the corresponding form fields.

That being said, normally crispy forms work quite well with ModelForms, so perhaps it is better to take a look what the problem is with your ModelForms and try to fix this over "circumventing" the problem, but making it harder to work with your forms.

Upvotes: 1

Related Questions