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


Wed 10 September 2014

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.


Share: