Skip to content

Instantly share code, notes, and snippets.

@baxeico
Last active August 28, 2021 19:39
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save baxeico/f641eaf9663f0f4122ea to your computer and use it in GitHub Desktop.
Save baxeico/f641eaf9663f0f4122ea to your computer and use it in GitHub Desktop.
A custom UpdateView to set initial data and save the user profile with a custom group field
from django.contrib.auth.models import User
from django.views.generic import UpdateView
from .forms import UserProfileForm
class UserProfileUpdateView(UpdateView):
model = User
def get_initial(self):
initial = super(UserProfileUpdateView, self).get_initial()
try:
current_group = self.object.groups.get()
except:
# exception can occur if the edited user has no groups
# or has more than one group
pass
else:
initial['group'] = current_group.pk
return initial
def get_form_class(self):
return UserProfileForm
def form_valid(self, form):
self.object.groups.clear()
self.object.groups.add(form.cleaned_data['group'])
return super(UserProfileUpdateView, self).form_valid(form)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment