简体   繁体   English

如何在Django中仅向帐户所有者显示配置文件编辑功能?

[英]How to show profile editing features only to account's owner in Django?

I'm building a website using Django 1.8.4 and I use django-registration-redux to handle users login and logout. 我正在使用Django 1.8.4构建网站,并使用django-registration-redux处理用户的登录和注销。

When all users are logged out, I manually enter a user's profile page, which contains users info and link to edit the profile: 当所有用户都注销后,我手动进入用户的个人资料页面,其中包含用户信息和编辑个人资料的链接:

url(r'^users/(?P<slug>\w+)/$', UserProfileDetailView.as_view(), name="profile")

problem is, when I visit a user's page (ie /users/james/) it recognizes me as user "james" logged in ( is_authenticated ) , and show logout and edit profile button, but it shouldn't! 问题是,当我访问用户页面(即/ users / james /)时,它会将我识别为已登录( is_authenticated )的用户“ james”,并显示注销和编辑配置文件按钮,但事实并非如此! it should only show public info. 它应该只显示公共信息。 (when I click edit button, it asks me for login credits, so that part works fine) (当我单击“编辑”按钮时,它会要求我提供登录信用,以便该部分正常工作)

How can I avoid this situation (showing edit profile, logout, etc. from either random logged in or anonymous users) and only show them to logged in owners of account? 如何避免这种情况(显示来自随机登录或匿名用户的编辑配置文件,注销等),而仅将其显示给已登录的帐户所有者?

viws.py viws.py

class UserProfileDetailView(DetailView):
    model       = get_user_model()
    slug_field  = "username"
    template_name = "user_detail.html"

    def get_object(self, queryset=None):
        user    = super(UserProfileDetailView, self).get_object(queryset)
        UserProfile.objects.get_or_create(user=user)
        return user

user_detail.html user_detail.html

<h2>{{ object.username }}'s Profile</h2>
{% if object.userprofile.bio %}
<div>
<b>Bio:</b>
{{ object.userprofile.bio }}
</div>
{% endif %}

{% if object.username == user.username and user.is_authenticated %}
    <p><a href='{% url "edit_profile" %}'>Edit My Profile</a></p>
{% endif %}

#footer
{% if user.is_authenticated %}
    <a href="{% url 'logout' %}">Logout</a> |
    <a href="{% url 'profile' slug=user.username %}"><b>{{ user.username }}</b></a> 
  {% else %}
    <a href="{% url 'registration_register' %}">Register</a> |
    <a href="{% url 'login' %}">Login</a> 
{% endif %}

The "user" variable in your template's context is being overwritten by the current record being viewed. 模板上下文中的“用户”变量被正在查看的当前记录覆盖。

Try changing 尝试改变

{% if object.username == user.username and user.is_authenticated %}

to

{% if object == request.user and request.user.is_authenticated %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM