pythondjangoauthenticationdjango-errors

Django error: name 'LOGIN_REDIRECT_URL' is not defined


I am trying to take advantage of the global variable LOGIN_REDIRECT_URL in the settings.py file in my Django project to avoid duplicating URLs everywhere.

In my settings.py I have redefined LOGIN_REDIRECT_URL like so:

LOGIN_REDIRECT_URL = "my_app_name:index"

I am trying to use LOGIN_REDIRECT_URL in my login_view in views.py as follows:

def login_view(request):
    form = LoginForm(data=request.POST)
    if form.is_valid():
        username = form.cleaned_data["username"]
        password = form.cleaned_data["password"]
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return HttpResponseRedirect(reverse(LOGIN_REDIRECT_URL))
    else: ...

However, when I log in I get the following error message:

name 'LOGIN_REDIRECT_URL' is not defined

I thought about importing LOGIN_REDIRECT_URL from settings.py but that feels wrong since other variables from there do not need to be imported anywhere.

What am I doing wrong?


Solution

  • You have to import the settings to use settings variables

    from django.conf import settings
    
    ...
    
    return HttpResponseRedirect(reverse(settings.LOGIN_REDIRECT_URL))