Search code examples
pythondjangodjango-modelsdjango-viewsdjango-users

Updating custom user (AbstractUser) in Django


I created a custom user using CBV and i have succeeded in implementing signup view however i am finding difficult to implement the update view. I have implemented the update view using the following code:

models.py

class CustomUser(AbstractUser):
   state = models.CharField(choices=States, default ='abia', max_length=50 )
   city = models.CharField(max_length=50)  
   local_government = models.CharField(max_length=50)  
   phone_number = models.CharField(max_length=50, blank= True)  
   picture = models.ImageField(upload_to='user/photos', blank=False, null=False, validators= 
    [clean_image])

forms.py

  class CustomUserCreationForm(UserCreationForm):

    class Meta:
      model = CustomUser
      fields = UserCreationForm.Meta.fields + ('state', 'city', 'local_government', 'phone_number', 
         'picture',)

  class CustomUserChangeForm(UserChangeForm):

    class Meta:
       model = CustomUser
       fields = UserCreationForm.Meta.fields + ('state', 'city', 'local_government', 'phone_number', 
       'picture',)

admin.py

 class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser

   list_display = ['id', 'first_name', 'last_name', 'email','subscription_plan', 'state', 'city', 
     'local_government', 'phone_number', 'picture']

views.py (update):

 class UpdateUser( LoginRequiredMixin, UpdateView):
   model = CustomUser
   form_class = CustomUserChangeForm
   template_name = 'profile/profile-edit.html'
   login_url = 'login'

The UpdateUser page just reload when i click to update profile without committing the update. Any help will be appreciated.


Solution

  • Since you are updating user object you should send the pk value to the URL tag in the template