使用基于类的 UpdateView 更新 Django 中的用户模型 [英] Updating User model in Django with class based UpdateView

查看:18
本文介绍了使用基于类的 UpdateView 更新 Django 中的用户模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用基于类的 UpdateView 更新 Django 用户模型,该模型会自动与当前用户一起呈现,但我收到一个错误,提示需要 pk 或 slug.表单工作并使用正确的当前用户上下文呈现,但在我尝试提交更改时抛出错误.以下是我正在使用的视图:

I am trying to update the Django User model with the class based UpdateView that automatically renders with the current user but am getting an error that a pk or slug is required. The form work and renders with the proper current user context but throws the error when I try to submit the changes. Below is the view I am using:

class UserUpdateView(UpdateView):
    form_class = UserForm
    model = User
    template_name = 'members/user_update.html'

    def get(self, request, **kwargs):
        self.object = User.objects.get(username=self.request.user)
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        context = self.get_context_data(object=self.object, form=form)
        return self.render_to_response(context)

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return HttpResponseRedirect(self.get_success_url())

推荐答案

我需要覆盖更新视图上的 get_object() 方法并且不需要覆盖 form_valid.自定义 get_object() 方法是:

I need to override the get_object() method on the update view and do not need to override form_valid. The custom get_object() method is:

    def get_object(self, queryset=None):
        return self.request.user

这篇关于使用基于类的 UpdateView 更新 Django 中的用户模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆