python - Django 编辑授权用户配置文件

标签 python django django-views django-authentication

我是 Django 的新手,正在用 Django 1.11 编写应用程序。

我想创建一个个人资料更新页面。

我已经创建了一个应用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 或 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() 部分

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.

关于python - Django 编辑授权用户配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46171584/

相关文章:

python - 使用python matplotlib时如何避免 "suptitle"和 "subplots"之间的重叠?

python - 比较字符串中的字符

django - PyCharm 无法识别我的 VirtualEnv 安装模块

python - 在 Django 中随机播种

python - 跨三个模型/表将 Python/Django View 写入 "join"

python - 函数缺少 2 个必需的位置参数 : 'x' and 'y'

python - reshape 热图的函数值

django - default_token_generator 如何存储 token ?

python - 如何在 Django URL 模式中使用小数?

Django - 带有控制数据的错误模型