LeLouch
LeLouch

Reputation: 611

View Profile page as another user in django

So I have a my user profile view you can see as a logged in user. I wanted to add a second view so other logged in users can visit profile pages as well, but I'm not really sure I'm doing it the right way

urls.py

url(r'^accounts/profile/', main_views.uprofile, name='uprofile'), #the page you see as my profile
    url(r'^profile/(?P<pk>\d+)/$', main_views.oprofile, name='oprofile'), # the page i use so other users can view the profile page
    url(r'^accounts/update/(?P<pk>\d+)/', User_Profile_views.edit_user, name='edit_user'), #Custom update profile page

main_views.py

@login_required(login_url='/accounts/login/')
def uprofile (request):

    context = locals()  
    template = 'profile.html'
    return render (request, template, context)

def oprofile (request, pk):
    user = User.objects.get(pk=pk)

    context = locals()  
    template = 'profile.html'
    return render (request, template, context)

Upvotes: 0

Views: 1993

Answers (1)

Ravi Ojha
Ravi Ojha

Reputation: 862

From product point of view, you would want to keep same url for both uprofile and oprofile. One simple reason being, when I visit my profile and if I want to share it with someone else, I'd just copy-paste the url.

How to do that?

In your view, pass a flag that helps your template to render the right elements. For instance, if the user is same as the profile being visited, pass a flag, say editable, and use it to show edit buttons. And instead of two views, you can have single view.

Also, instead of id, people tend to remember their username/handle. So it's better to have username. However, make sure you have unique username for all users.

urls.py

url(r'^profile/(?P<username>[\w\-]+)/$', main_views.profile, name='profile'),

views.py

def profile (request, username):
    # If no such user exists raise 404
    try:
        user = User.objects.get(username=username)
    except:
        raise Http404

    # Flag that determines if we should show editable elements in template
    editable = False
    # Handling non authenticated user for obvious reasons
    if request.user.is_authenticated() and request.user == user:
        editable = True

    context = locals()
    template = 'profile.html'
    return render (request, template, context)

Upvotes: 2

Related Questions