How to add a group choice combo box in a Django user profile form

Assume that you have a Django project where each user belongs to just one group, say Registered or Admin, but not both.

You want to show a form in your front-end to let Admin users edit the user profiles, where each user profile is made with First name, Last name, Email and the user group.

This task can be accomplished very easily! What you need is a customized ModelForm to add the possibility to edit the user group together with the other fields, and a customized UpdateView to let you set the form initial data for the group field, and to save the changes correctly.

Here is the ModelForm:

That is a standard ModelForm for the User model, we have just added a group field that is a ModelChoiceField, that is a combo box with all available groups in our project as choices, if you want you can filter the queryset according to your needs. We have also restricted the fields shown in the user profile form to First name, Last name, Email and Group.

This is the view we’ll use to update the user profile. We have overridden some methods of UpdateView:

  • get_initial is used to set the initial value for the custom group field with the current group the user belongs to. Note that when the user profile is edited for the first time the user will not belong to any group, but this is taken into account and no initial value will be provided to the field;
  • get_form_class is used to set the class used by the UpdateView to show and validate the form. We have set it to the one we created before;
  • form_valid is called by the UpdateView when the form submitted is valid. Here we remove the old group the user belonged to, and we add the new group selected in the form to the user. Remember that the groups field of the User model is a ManyToManyField, so we are simply using the Django ORM here.

That’s it, I hope that this how-to helps you with your Django project! Please let me know if you found my approach useful in the comments.

Advertisements

5 thoughts on “How to add a group choice combo box in a Django user profile form

  1. With havin so much content do you ever run into any problems of plagorism or copyright violation? My site has a lot of unique content I’ve either authored myself
    or outsourced but it appears a lot of it is popping it up all over the internet without my permission. Do you know any solutions
    to help prevent content from being stolen? I’d genuinely appreciate it.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s