Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PasswordChangeForm with Custom User Model

I recently implemented my own user model by subclassing abstract user.

class NewUserModel(AbstractUser):

After I did this the PasswordChangeForm stopped working. I fixed the issue in the UserCreationForm by overriding the class Meta: model field. However, the ChangePasswordForm doesn't specify a model and I can't see any reason why it shouldn't work with the new user model.

views.py

class PasswordChangeView(LoginRequiredMixin, FormView):
    template_name = 'change_password.html'
    form_class = PasswordChangeForm

    def get_form_kwargs(self):
        kwargs = super(PasswordChangeView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs
like image 964
Colton Allen Avatar asked Oct 20 '14 01:10

Colton Allen


People also ask

How do I change user model in Django?

Add "accounts" at the bottom of "INSTALLED_APPS". And add the "AUTH_PROFILE_MODULE" config at the bottom of the entire file. We will add "accounts" app in settings.py and use the "AUTH_USER_MODEL" config to tell Django to use our another model. And our another model will UserProfile.

What is Auth_user_model in Django?

Django allows you to override the default user model by providing a value for the AUTH_USER_MODEL setting that references a custom model. Method 2 – AUTH_USER_MODEL : AUTH_USER_MODEL is the recommended approach when referring to a user model in a models.py file.


2 Answers

Just spent most of the day trying to achieve this. Eventually I found out it was pretty simple to implement it with a FBV:

@login_required
def UpdatePassword(request):
    form = PasswordChangeForm(user=request.user)

    if request.method == 'POST':
        form = PasswordChangeForm(user=request.user, data=request.POST)
        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)

    return render(request, 'user/password.html', {
        'form': form,
    })
like image 127
Thomas Maurin Avatar answered Oct 14 '22 00:10

Thomas Maurin


CBV version:

    class PasswordChangeView(LoginRequiredMixin, FormView):
        model = CustomUser
        form_class = PasswordChangeForm
        template_name = 'password_change.html'

        def get_form_kwargs(self):
            kwargs = super(PasswordChangeView, self).get_form_kwargs()
            kwargs['user'] = self.request.user
            if self.request.method == 'POST':
                kwargs['data'] = self.request.POST
            return kwargs

        def form_valid(self, form):
            form.save()
            update_session_auth_hash(self.request, form.user)        
            return super(PasswordChangeView, self).form_valid(form)    
like image 45
FDN Avatar answered Oct 14 '22 00:10

FDN