Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, Redirecting staff from login to the admin site

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.

like image 286
Francisco Gomez Avatar asked Jan 31 '26 12:01

Francisco Gomez


1 Answers

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.

like image 142
un33k Avatar answered Feb 03 '26 05:02

un33k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!