Search code examples
pythondjangodjango-templatesdjango-registration

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.

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 (i.e. /users/james/) it recognizes me as user "james" logged in (is_authenticated) , and show logout and edit profile button, but it shouldn't! 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

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 %}

Solution

  • 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 %}