Django编辑身份验证用户配置

2024-04-20 01:00:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Django和用django1.11编写应用程序是新手。在

我想创建一个Profile update页面。在

我已经创建了一个应用程序accounts来管理所有与概要文件相关的活动并创建了一个类

from django.contrib.auth.models import User

# Create your views here.
from django.views.generic import TemplateView, UpdateView


class ProfileView(TemplateView):
    template_name = 'accounts/profile.html'


class ChangePasswordView(TemplateView):
    template_name = 'accounts/change_password.html'


class UpdateProfile(UpdateView):
    model = User
    fields = ['first_name', 'last_name']

    template_name = 'accounts/update.html'

myapp/accounts/urls.py

^{pr2}$

当我访问127.0.0.1:8000/accounts/update时,它给出

AttributeError at /accounts/update/

Generic detail view UpdateProfile must be called with either an object pk or a slug.

因为,我希望登录的用户编辑他/她的配置文件信息。我不想在url中传递pk。在

如何在django1.11中创建配置文件更新页面?


Tags: djangonamefromimport应用程序htmlupdatetemplate
1条回答
网友
1楼 · 发布于 2024-04-20 01:00:59
class UpdateProfile(UpdateView):
    model = User
    fields = ['first_name', 'last_name']

    template_name = 'accounts/update.html'

    def get_object(self):
        return self.request.user

正如错误告诉你的那样,如果你不精确目标,你必须返回一个pk或slug。因此,通过重写get_object方法,可以告诉django要更新哪个对象。在

如果您想换一种方式,可以在url中发送对象的pk或slug:

^{pr2}$

在这里,默认的get_object方法将捕捉args中的pk并找到要更新的用户。在

请注意,第一种方法只有在用户想要更新其配置文件并经过身份验证(self.request.user)的情况下才有效,第二种方法允许您实际更新您想要的任何用户,只要您有了这个用户的pk(accounts/update/1,将用pk=1更新用户,等等…)。在

某些文档here,get_object()部分

Returns the object the view is displaying. By default this requires self.queryset and a pk or slug argument in the URLconf, but subclasses can override this to return any object.

相关问题 更多 >