djangodjango-admin-filters

Login redirecting to specific page based on specific group in template


I have two admin groups in django-admin[staff, student]. I want that whenever a user wants to log in, the program first checks that to which group the user belongs, then redirect each one to a particular page.

index.html

<form method="post" action="{% url 'users:login' %}" class="form">
{% csrf_token %}
    {% bootstrap_form form %}
    {% buttons %}
    <button name="submit" class="btn btn-primary mt-2">Log in</button>
    {% endbuttons %}
    
    <input type="hidden" name="next" value="{% url 'student_paper:index' %}" />
</form>

Solution

  • You can create your custom login_view:

    Here's an example and also for more info see Django docs.

    from django.contrib.auth import authenticate, login
    
    def my_login_view(request):
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            if user.is_staff:
                # Redirect to a success staff page.
            else:
                # Redirect to a success page.
            ...
        else:
            # Return an 'invalid login' error message.
            ...