[Answered ]-Show only the user profile of the logged in user to the logged in user

1πŸ‘

βœ…

If i got the question then the most easy way (as per me) is to use decorators.

Use a login decorator to allow a route only when the user is logged in.

from django.contrib.auth.decorators import login_required

# then at the user_detail route i.e, the route which shows the profile of a user.

@login_required(login_url='your_login_route') #'your_login_route' is the route of your login page. So if a user is not logged in, he will be redurected to 'your_login_route'
def user_detail(request, user_id):
    ...

EDIT: If you only want to show the profile to the same user and not to any other user you can try this;

def user_detail(request, user_id):
    if request.user.id == user_id:
        "show the profile"
    else:
        'show an error page'

Please make sure that the user_id which you are using for recognition is same as the user’s id in database.

πŸ‘€Irfan wani

0πŸ‘

You can do like this.

@login_required
def user_detail(request, user_id):
        user = request.user
        return render (request, 'users/user_detail_2.html',{'user':user})

Or you can use request.user in templates, but you have to check the user is_authenticated.

πŸ‘€yanqzhi

0πŸ‘

class MyView(DetailView):
    Model = User
    def get_object(self):
        """get obj here, either slug or pk"""

    def get_context_data(self, **kwargs):
        context = super(MyView, self).get_context_data(**kwargs)
        context['user'] = self.object.filter(user=request.user)
        return context
πŸ‘€Jonas Moloto

Leave a comment