dannyxn
dannyxn

Reputation: 422

Setting inital form data

Below I paste snippet of user's profile edition view, I think it isn't necessary to paste all view here. I want to set initial data, when user want to edit his profile he should see data which is actually stored in database.

form = UserProfileForm(initial={'first_name': user.userprofile.first_name,
                                    'last_name': user.userprofile.last_name,
                                    'nickname': user.userprofile.nickname,
                                    'bio': user.userprofile.bio,
                                    'location': user.userprofile.location,
                                    'gender': user.userprofile.gender,
                                    'birth_date': user.userprofile.birth_date})

I've created above code and it works fine, but I think it isn't pythonic at all, so my request is about how can I write it better?

Upvotes: 0

Views: 37

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599600

Rather than using initial data, you should pass the userprofile itself as the instance parameter:

form = UserProfileForm(instance=user.userprofile)

assuming that UserProfileForm is a ModelForm, which it should be.

Upvotes: 2

Related Questions