[Answer]-Automatic HTTPRedirect in Django view if user is authenticated?

1👍

You can try this :

def profile_page(request, username):
    if request.user.is_authenticated():
        if request.user.username == username:
            # removed user since already in request.user and available in template as 'user'
            # removed taskitems since directly available in template as 'user.taskitem_set.all'
            return render(request, 'profile.html')
        else:
            return HttpResponseRedirect(reverse('profile_page', args=(request.user.username,)))
    else:
        return render(request, 'login.html')

0👍

Remove the username parameter since each user should only view their own profile. You can also use the login_required decorator to remove the extra conditional:

from django.contrib.auth.decorators import login_required
from django.shortcuts import render

@login_required
def profile_page(request):
    return render(request, 'profile.html')

Make sure to set LOGIN_URL in your settings.py so unauthenticated users get redirected to the right spot.

Leave a comment