How to Specify the URL for the login_required Decorator in Django



Python


In this article, we show how to specify the URL for the login_required decorator in Django.

The login_required decorator is a decorator that can be used in Django that requires a view to have the user logged in. If the user is not logged in, the user will automatically be redirected to the login page (so that the person can log in).

The login_required decorator, thus, forces a user to log in. If a user goes to a page that has a login_required decorator and is not logged in, that person will be redirected to the login page.

So how can we specify the URL that a user gets redirected to?

By default, the URL that a website visitor gets redirected to is '/accounts/login'

This is the default set by Django.

However, you may not have put have created an app called accounts and put your login view within this app. Therefore, using the default URL provided by Django will result in a 404 page not found error.

To specify your own URL that the login view is located in, you have one of two options.

For global scope within all the apps in your project, you can go to the settings.py file and specify the LOGIN_URL variable.

Let's say you want to set your login URL to '/users/login', this is what would be in your settings.py file.



Now if you put a login_required decorator on any function within a views.py file in any of your apps, the person, if not logged in, will be redirected to the /users/login URL if visiting that view.

Doing it this way is normally recommended since a site normally only has one login page. Thus, LOGIN_URL, by nature, is global.

However, you don't have to give the LOGIN_URL global scope. You can also give it local scope.

When you place the login_required decorator on a function within a view (in your views.py file), you can specify with this decorator, the URL that you want the user to be redirected to.



So you can see that within the login_required decorator, we placed within parentheses the login_url. By convention, this is done in lowercase characters, since it has local scope.

Keep in mind that if you have a LOGIN_URL specified in your settings.py file and a login_url specified within the decorator call, the login_url (local scope) has precedence over the variable specified in the settings.py file. The local variable will override the global variable, in this case.

And this is how you can specify the URL For the login_required decorator in Django, to be redirected to the login page of your website.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...