在 Django 中创建用户个人资料页面

2024-05-06

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


您只需要创建一个可供经过身份验证的用户使用的视图,并返回一个配置文件编辑表单(如果他们正在创建一个)GET请求或更新用户的个人资料数据(如果他们正在创建)POST要求。

大部分工作已经为您完成,因为有通用视图 https://docs.djangoproject.com/en/dev/topics/class-based-views/用于编辑模型,例如更新视图 https://docs.djangoproject.com/en/dev/ref/class-based-views/#updateview。您需要扩展的是检查经过身份验证的用户并向其提供您想要提供编辑的对象。这是 MTV 三元组中的视图组件,提供编辑用户个人资料的行为 -Profile模型将定义用户资料 https://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users模板将单独提供演示文稿。

因此,这里有一些行为可以作为简单的解决方案:

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!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Django 中创建用户个人资料页面 的相关文章

随机推荐