[Answer]-How can I redirect a user to a specific page or run some code logic in a common place after login in Django?

1👍

Django provides decorator called, login_required() which we can attach to any view, where we require the user to be logged in. If a user is not logged in and they try to access a page which calls that view, then the user is redirected to another page which you can set, typically the login page.The following is an example code for a view called restricted.

@login_required
def restricted(request):
    return HttpResponse("since you are logged in you can see this page)

Note that to use a decorator, you place it directly above the function signature, and put a @ before naming the decorator. Python will execute the decorator before executing the code of your function/method. To use the decorator you will have to import it, so also add the following import:

from django.contrib.auth.decorators import login_required

To set a page to which the user is redirected if he is not logged in, you need to add the something like this to settings.py

LOGIN_URL = "/app_name/login/"

This ensures that the login_required() decorator will redirect any user not logged in to the URL /app_name/login/.

0👍

I redirected by groupwise as :

from django.http import HttpResponseRedirect
def loggedin_view(request):
    usergroup = None
    if request.user.is_authenticated():
        usergroup = request.user.groups.values_list('name', flat=True).first()
    if usergroup == "staffGroup":
        return HttpResponseRedirect("/cmit/userDash")
    elif usergroup == "supervisorGroup":
        return HttpResponseRedirect("/cmit/supervisorDash")
    elif usergroup == "auditGroup":
        return HttpResponseRedirect("/cmit/auditDash")
    elif usergroup == "mgtGroup":
        return HttpResponseRedirect("/cmit/mgtDash")
    else:
        return HttpResponseRedirect("/admin/")

Leave a comment