I'm using Django 1.8.4 and Django-registration-redux for handling user registration. My problem is:
when a user logged in, i.e. james, I want to show his username in toolbar. But the problem is when I visit another user's profile,i.e. mike, the username in toolbar also changes to mike. Which is absolutely forbidden.
I'm getting logged in user as an object in my views to check if the logged in user is same as user's profile is currently visited.
I'm not sure if I should prevent request.user to change in different contexts or there's a problem in my codes:
urls.py
url(r'^users/(?P<slug>\w+)/$', UserProfileDetailView.as_view(), name="profile"),
views.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
base.html
{% if user.is_authenticated %}
<a href="{% url 'link_create' %}">Submit Link</a> |
<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_detail.html
{% if object == request.user and request.user.is_authenticated %}
<p><a href='{% url "edit_profile" %}'>Edit My Profile</a></p>
{% endif %}
There are 2 users in your context:
object
(or user
- DetailView
will also return current object on lowercased model name) this is user you're viewingrequest.user
- this is current logged in userYou've used user.name
in toolbar instead of request.user.name
. That is causing issues.