【问题标题】:Creating user profile pages in Django在 Django 中创建用户个人资料页面
【发布时间】:2012-02-21 05:22:06
【问题描述】:

我是 Django 的初学者。我需要建立一个网站,每个用户都有一个个人资料页面。我见过 django 管理员。用户的个人资料页面,应该存储一些只能由用户编辑的信息。谁能指出我怎么可能?任何教程链接都会非常有帮助。此外,是否有任何用于 django 的模块,可用于设置用户页面。

【问题讨论】:

标签: django django-models


【解决方案1】:

您只需要创建一个可供经过身份验证的用户使用的视图,如果他们正在创建 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 丢失的错误。
  • 感谢@PhilGyford,我一定会应用您的更改。
【解决方案2】:

你可以

  • 创建另一个模型来存储用户的个人资料信息
  • 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    • 2011-01-25
    • 2018-12-09
    • 2016-10-30
    相关资源
    最近更新 更多