'Django: authenticate & login function works but user isn't actually logged in
i have a problem related to logging a user in in Django.
in the lines of code below, i have tried to use the login function to log the user in, but when the user gets to the main page the page tells them to log in (meaning that django told me that they're not authenticated); the login function doesn't raise any errors at all.
login/login.py
def login_user(request):
if request.method == "POST":
form = forms.Login(request.POST)
if form.is_valid():
username = request.POST['username']
password = request.POST['password']
db_user = AuthBackend().authenticate(request, username=username, password=password)
if db_user is not None:
login(request, db_user, backend="django.contrib.auth.backends.ModelBackend")
return HttpResponseRedirect(reverse("main:index"))
else:
return render(request, "login/login.html", {"form": form, "error": "Incorrect"})
else:
return render(request, "login/login.html", {"form": form})
return render(request, "login/login.html", {"form": forms.Login()})
main/templates/main/index.html
<!DOCTYPE html>
<html>
<head>
<title>Timeline</title>
</head>
<body>
{% if user.is_authenticated %}
<a href="{% url 'account' %}">Account</a>
{% else %}
<a href="{% url 'login:login' %}">Log In</a>
{% endif %}
</body>
</html>
also, im very new to stack and making questions, so if i have to provide other info i would appreciate the reminder and ill try to be helpful as possible. thanks
Solution 1:[1]
Try this in login.py:
...
from django.contrib.auth import authenticate, login, logout
def login_user(request):
if request.method == "POST":
form = forms.Login(request.POST)
if form.is_valid():
username = request.POST['username']
password = request.POST['password']
db_user = authenticate(request, username=username, password=password)
if db_user is not None:
login(request, db_user)
return HttpResponseRedirect(reverse("main:index"))
else:
return render(request, "login/login.html", {"form": form, "error": "Incorrect"})
else:
return render(request, "login/login.html", {"form": form})
return render(request, "login/login.html", {"form": forms.Login()})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | onapte |
