【发布时间】:2012-02-21 05:22:06
【问题描述】:
我是 Django 的初学者。我需要建立一个网站,每个用户都有一个个人资料页面。我见过 django 管理员。用户的个人资料页面,应该存储一些只能由用户编辑的信息。谁能指出我怎么可能?任何教程链接都会非常有帮助。此外,是否有任何用于 django 的模块,可用于设置用户页面。
【问题讨论】:
-
你已经开发了什么?
标签: django django-models
我是 Django 的初学者。我需要建立一个网站,每个用户都有一个个人资料页面。我见过 django 管理员。用户的个人资料页面,应该存储一些只能由用户编辑的信息。谁能指出我怎么可能?任何教程链接都会非常有帮助。此外,是否有任何用于 django 的模块,可用于设置用户页面。
【问题讨论】:
标签: django django-models
您只需要创建一个可供经过身份验证的用户使用的视图,如果他们正在创建 GET 请求,则返回一个配置文件编辑表单,或者如果他们正在创建 POST 请求,则更新用户的配置文件数据。
大部分工作已经为您完成,因为有 generic views 用于编辑模型,例如 UpdateView。您需要扩展它的是检查经过身份验证的用户并向其提供您要为其提供编辑的对象。这是 MTV 三元组中的视图组件,它提供编辑用户个人资料的行为——Profile 模型将定义 user profile,而模板将离散地提供演示。
所以这里有一些行为可以作为一个简单的解决方案:
from django.contrib.auth.decorators import login_required
from django.views.generic.detail import SingleObjectMixin
from django.views.generic import UpdateView
from django.utils.decorators import method_decorator
from myapp.models import Profile
class ProfileObjectMixin(SingleObjectMixin):
"""
Provides views with the current user's profile.
"""
model = Profile
def get_object(self):
"""Return's the current users profile."""
try:
return self.request.user.get_profile()
except Profile.DoesNotExist:
raise NotImplemented(
"What if the user doesn't have an associated profile?")
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
"""Ensures that only authenticated users can access the view."""
klass = ProfileObjectMixin
return super(klass, self).dispatch(request, *args, **kwargs)
class ProfileUpdateView(ProfileObjectMixin, UpdateView):
"""
A view that displays a form for editing a user's profile.
Uses a form dynamically created for the `Profile` model and
the default model's update template.
"""
pass # That's All Folks!
【讨论】:
@method_decorator(login_required)(从django.utils.decorators导入)而不是@login_required。并且不要使用BaseUpdateView,而是使用UpdateView,否则会出现关于render_to_response 丢失的错误。
你可以
AUTH_PROFILE_MODULE='yourprofileapp.ProfileModel' 添加到settings.py在个人资料编辑视图中,只允许登录用户编辑自己的个人资料
示例:
@login_required
def edit_profile(request):
'''
edit profile of logged in user i.e request.user
'''
您还可以确保每当创建新用户时,也使用 django 的信号创建用户的配置文件
从 django 文档中了解 storing additional information about users
【讨论】: