我最近通过继承抽象用户来实现我自己的用户模型。
class NewUserModel(AbstractUser):
我这样做后PasswordChangeForm
停止了工作。我通过覆盖UserCreationForm
模型字段修复了class Meta:
中的问题。但是,ChangePasswordForm
没有指定模型,我看不出为什么它不适用于新用户模型的任何原因。
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
答案 0 :(得分:8)
一天大部分时间都在努力实现这一目标。最终我发现用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,
})
答案 1 :(得分:1)
CBV版本:
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)