skip to Main Content

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.


Freelance developer and sysadmin

This Post Has 7 Comments
  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.

  2. I used this code and I only got to select the group but the selection I make is not saved to the database.

    1. Group saving is done in the form_valid method of the class based view. Please check that your View is set up correctly.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top