Django编辑auth用户配置文件

时间:2017-09-12 08:33:06

标签: python django django-views django-authentication

我是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.

因为,我希望登录用户编辑他/她的个人资料信息。我不想在网址中传递pk

如何在Django 1.11中创建个人资料更新页面?

1 个答案:

答案 0 :(得分:1)

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您要更新哪个对象。

如果您希望以其他方式进行,可以在网址中发送对象的pk或slug:

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更新用户等...)。

某些文档here,get_object()部分

  

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