Search code examples
djangodjango-templatesdjango-usersdjango-generic-views

Django Class Based Views Profile view, can't distinguish between user logged in and user being modified in a template


I'm trying to create a user dashboard, and the first thing I'm implementing is the user profile. All the profiles are meant to be public, and I want to add an Edit button if the user is visiting their own profile. My problem is that when I go onto someone's page, it replaces the user variable with the user I'm seeing the profile of.

My url:

url(r'^profile/(?P<pk>\d+)$',
    views.ProfileView.as_view(),
    name='profile'),

I created a view:

from django.contrib.auth import get_user_model()
from django.views.generic.detail import DetailView

class ProfileView(DetailView):
    model = get_user_model()
    template_name = 'accounts/profile.html'

And in my template:

{% if user == object %}user and object are the same{% endif %}

I am seeing user and object are the same when the current user is on their own profile, but it also works when the current user is seeing another profile. Is there something I've missed? Why are they the same?


Solution

  • The user variable is injected by the django.contrib.auth.context_processors.auth context processor.

    To solve this issue set the context_object_name to non "user" string:

    class ProfileView(DetailView):
        model = get_user_model()
        context_object_name = 'user_object'
        template_name = 'accounts/profile.html'
    

    And then use this name in the template:

    {% if user == user_object %}user and object are the same{% endif %}