Django编辑验证用户配置文件



我是Django的新手,并在Django 1.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

from django.conf.urls import url
from . import views
app_name = 'accounts'
urlpatterns = [
    url(r'^$', views.ProfileView.as_view(), name='profile'),
    url(r'^profile/', views.ProfileView.as_view(), name='profile'),
    url(r'^change_password/', views.ChangePasswordView.as_view(), name='change_password'),
    url(r'^update/', views.UpdateProfile.as_view(), name='update'),
    url(r'^setting/', views.SettingView.as_view(), name='setting')
]

当我访问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

如何在Django 1.11中创建配置文件更新页面?

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或sl。

url(r'^update/(?P<pk>d+)', views.UpdateProfile.as_view(), name='update')

在这里,默认的get_object方法将捕获ARGS中的PK,并找到要更新的用户。

请注意,如果用户想更新他的个人资料并经过身份验证(self.request.user),则仅第一种方法(如我所写),第二种方法允许您实际上更新所需的任何用户,一旦您拥有此用户的PK(accounts/update/1,将使用pk = 1等更新用户。

一些文档在这里,get_object()e节

返回视图显示的对象。 默认情况下,这需要self.querysetpkslug参数 在urlconf中,但是子类可以覆盖以返回任何对象。

最新更新