在Django中创建用户个人资料页面 [英] Creating user profile pages in Django

查看:76
本文介绍了在Django中创建用户个人资料页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm a beginner in Django. I need to setup a website, where each user has a profile page. I've seen django admin. The profile page for users, should store some information which can be edited by the user only. Can anyone point me out how that is possible?. Any tutorial links would be really helpful. Also, are there any modules for django, which can be used for setting up user page.

推荐答案

您只需要创建一个供身份验证用户使用的视图,并在创建用户时返回个人资料编辑表单 GET 请求,或者如果用户正在创建 POST 请求,则更新用户的个人资料数据。

You would just need to create a view that's available to an authenticated user and return a profile editing form if they're creating a GET request or update the user's profile data if they're creating a POST request.

大多数工作已经为您完成,因为有通用视图以编辑模型,例如 UpdateView 。您需要扩展的内容是检查经过身份验证的用户,并为其提供要为其提供编辑的对象。这是MTV三合会中的视图组件,提供了编辑用户个人资料的行为-个人资料模型将定义用户个人资料,模板将单独提供演示文稿。

Most of the work is already done for you because there are generic views for editing models, such as the UpdateView. What you need to expand that with is checking for authenticated users and providing it with the object that you want to provide editing for. That's the view component in the MTV triad that provides the behavior for editing a user's profile--the Profile model will define the user profile and the template will provide the presentation discretely.

因此,有一些行为可作为一种简单的解决方案扔给您:

So here's some behavior to throw at you as a simple solution:

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!

这篇关于在Django中创建用户个人资料页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆