Last active
August 28, 2021 19:39
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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