AxesBackend requires a request as an argument to authenticate
I need to add a restriction on account login attempts to my django site, I found the popular django-axes library, followed the documentation and code examples, but when I try to log in to my account (whether the password is correct or not) I get the error AxesBackend requires a request as an argument to authenticate even though my code follows the instructions exactly and I'm passing the request. Here is all the code that is somehow related to this:
settings.py
INSTALLED_APPS = [
...
'axes',
]
MIDDLEWARE = [
...
'axes.middleware.AxesMiddleware',
]
AXES_FAILURE_LIMIT = 4
AXES_RESET_ON_SUCCESS = True
AXES_COOLOFF_TIME = 1
AUTHENTICATION_BACKENDS = [
'axes.backends.AxesBackend', # Axes must be first
'django.contrib.auth.backends.ModelBackend',
]
AUTH_USER_MODEL = "users.User"
LOGIN_URL = "/user/login/"
views.py
from django.contrib import auth, messages
def login(request):
if request.method == "POST":
form = UserLoginForm(data=request.POST)
if form.is_valid():
username = request.POST["username"]
password = request.POST["password"]
user = auth.authenticate(request=request, username=username, password=password)
if user:
auth.login(request, user)
redirect_page = request.POST.get("next", None)
if redirect_page and redirect_page != reverse("user:logout"):
return HttpResponseRedirect(request.POST.get("next"))
return HttpResponseRedirect(reverse("main:main_page"))
else:
form = UserLoginForm()
context = {"title": "Вход", "form": form}
return render(request, "users/login.html", context)
Django==5.0.4
django-axes==6.5.2
I would be very grateful for your help!
Indicated above.
Here is the exact output in the console that I received:
File "c:\Users\danii\OneDrive\Рабочий стол\coins\Project Bismuth\venv\Lib\site-packages\axes\backends.py", line 46, in authenticate
File "c:\Users\danii\OneDrive\Рабочий стол\coins\Project Bismuth\venv\Lib\site-packages\axes\backends.py", line 46, in authenticate
raise AxesBackendRequestParameterRequired(
axes.exceptions.AxesBackendRequestParameterRequired: AxesBackend requires a request as an argument to authenticate
[06/Oct/2024 18:43:22] "POST /user/login/ HTTP/1.1" 500 125738
The reason it fails is because your UserLoginForm
already tries to authenticate()
, and that fails because it has no request
object.
The good news is: we can let the form handle it with the request, like:
from django.urls import redirect
def login(request):
if request.method == 'POST':
form = UserLoginForm(request=request, data=request.POST)
if form.is_valid():
user = form.get_user()
if user:
auth.login(request, user)
redirect_page = request.POST.get('next', None)
if redirect_page and redirect_page != reverse('user:logout'):
return HttpResponseRedirect(request.POST.get('next'))
return redirect('main:main_page')
else:
form = UserLoginForm()
context = {'title': 'Вход', 'form': form}
return render(request, 'users/login.html', context)