我是 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.querysetand apkorslugargument in the URLconf, but subclasses can override this to return any object.
