2👍
You’ve got some different things going on that are affecting it.
Your urls.py
file needs some cleaning up. Because you’ve defined your own login/logout methods, you don’t need to use the ones from django.contrib.auth.views
. So your base urls.py
file should look like this:
from django.conf.urls import url
from django.contrib import admin
import login.views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^home/', include('login.urls')
url(r'^$', login.views.login)
url(r'^logout/$', login.views.logout)
]
Your login/urls.py
file can stay the same. Now we are pointing login/logout to your views not the django.contrib.auth.views
.
You have settings.LOGIN_URL
set to login/
but your urls.py
file directs /
to the login function. For this answer, I’m changing settings.LOGIN_URL
to /
to match your url file.
Your login/views.py
file only needed a few changes now that we’ve updated the urls.py
file.
I cleaned up some of the import statements that were unnecessary and I removed redirect_field_name='next'
from @login_required
because 'next'
is the default value.
We need to check both the POST
and GET
objects to get the next
parameter.
The biggest change is after we authenticate the user and validate that they’re active, instead of return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
we just do return HttpResponseRedirect('/home')
or send them to the next
url that we grabbed from the POST
/GET
data.
from django.shortcuts import render
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
def login(request):
next = request.POST.get('next', request.GET.get('next', ''))
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = auth.authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
if next:
return HttpResponseRedirect(next)
return HttpResponseRedirect('/home')
else:
return HttpResponse('Inactive user')
else:
return HttpResponseRedirect(settings.LOGIN_URL)
return render(request, "login.html")
def logout(request):
auth.logout(request)
# Redirect back to login page
return HttpResponseRedirect(settings.LOGIN_URL)
@login_required
def home(request):
return render(request, "home.html")
Once you have that, unless there’s something else I’m missing, @login_required
should properly redirect to your login page if the user isn’t logged in.