开发者

Django, Redirecting staff from login to the admin site

开发者 https://www.devze.com 2022-12-31 21:17 出处:网络
So my site basically has 2 kinds of ways to login, one of them is for the common users, who get the regular screen that asks them for username and password, the other way its for staff.

So my site basically has 2 kinds of ways to login, one of them is for the common users, who get the regular screen that asks them for username and password, the other way its for staff.

The staff login should redirect them to the admin site after logging in, but for some reason the redirect doesnt happen, it stays on the same login page.

I use this condition on the login view.

开发者_运维问答
if user is not None and user.is_active and user.is_staff:
        auth.login(request,user)
        return HttpResponseRedirect("/admin/")

The admin site its up and running in my url configuration and everything, but i dont know if this is the correct way to redirect to the admin site already on session.

Thanks, any help would be appreciated.


When a user logs in, login() will automatically redirect the user skipping the following line in your code:

return HttpResponseRedirect("/admin/")

Two possibilities:

  1. If REDIRECT_FIELD_NAME (aka 'next') exists in your REQUEST fields, then the user is redirected to it right away.

  2. If REDIRECT_FIELD_NAME is not found, then the user is redirected to LOGIN_REDIRECT_URL which you may have defined in your settings.py & if not, then it redirects to the default value for LOGIN_REDIRECT_URL.

So, it seems that your code doesn't set REDIRECT_FIELD_NAME, so naturally all users will end up being redirected to the path of LOGIN_REDIRECT_URL whatever that may be.

To solve this, set request.REQUEST['next'] = '/admin/' when you know the user is staff. Then the redirect will happen automatically.


One way of logging in the the users and redirecting them according to their status could be:

from django.shortcuts import redirect
from django.contrib.auth import authenticate, login


def user_login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)

        if user.is_active:    
        # Redirecting to the required login according to user status.
            if user.is_superuser or user.is_staff:
                login(request, user)
                return redirect('/admin/')  # or your url name
            else:
                login(request, user)
                return redirect('/')  
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号