如何仅向 Django 中的帐户所有者显示个人资料编辑功能?
How to show profile editing features only to account's owner in Django?
我正在使用 Django 1.8.4 构建一个网站,我使用 django-registration-redux 来处理用户登录和注销。
当所有用户都注销后,我手动进入用户的个人资料页面,其中包含用户信息和link编辑个人资料:
url(r'^users/(?P<slug>\w+)/$', UserProfileDetailView.as_view(), name="profile")
问题是,当我访问用户页面(即 /users/james/)时,它会将我识别为用户 "james" 登录(is_authenticated
),并显示注销和编辑个人资料按钮,但不应该!它应该只显示 public 信息。 (当我点击编辑按钮时,它要求我输入登录信用,所以这部分工作正常)
如何避免这种情况(显示编辑配置文件、注销等来自随机登录或匿名用户的信息)并且只显示给登录的帐户所有者?
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
<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 %}
模板上下文中的 "user" 变量正在被正在查看的当前记录覆盖。
尝试改变
{% if object.username == user.username and user.is_authenticated %}
至
{% if object == request.user and request.user.is_authenticated %}
我正在使用 Django 1.8.4 构建一个网站,我使用 django-registration-redux 来处理用户登录和注销。
当所有用户都注销后,我手动进入用户的个人资料页面,其中包含用户信息和link编辑个人资料:
url(r'^users/(?P<slug>\w+)/$', UserProfileDetailView.as_view(), name="profile")
问题是,当我访问用户页面(即 /users/james/)时,它会将我识别为用户 "james" 登录(is_authenticated
),并显示注销和编辑个人资料按钮,但不应该!它应该只显示 public 信息。 (当我点击编辑按钮时,它要求我输入登录信用,所以这部分工作正常)
如何避免这种情况(显示编辑配置文件、注销等来自随机登录或匿名用户的信息)并且只显示给登录的帐户所有者?
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
<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 %}
模板上下文中的 "user" 变量正在被正在查看的当前记录覆盖。
尝试改变
{% if object.username == user.username and user.is_authenticated %}
至
{% if object == request.user and request.user.is_authenticated %}