Django how to count failed login attempt for prevent brute force attack?

I know there have few package available like django-defender, django-axes etc for prevent brute force attack. I am thinking to prevent brute force attack by showing captcha using Django session ( I want to use session for count failed login attempts) or somethings like this without help of any package . I want to count failed login attempt in my views then it will show the captcha after number of failed login attempts. So it will be simple two step:

step1) it will count the failed login attempts.

step2) It will show the captcha after number of failed login attempts

here is my views.py :

def login_view(request):
     if request.method == 'POST':
            username = request.POST.get('username')
            password =request.POST.get('password')
            user = authenticate(request, username=username, password=password)
            
            if user is not None:
                  login(request, user)
                  messages.add_message(request, messages.INFO,'Login Sucessfull')  
            else:
                  messages.info(request, "wrong username or password")

I actually found a code in one of my projects that should help you get started. This one counts page loads for given session, but with small tweaks can be used to count login attempts.

    if "load_count" in request.session:
        count = request.session["load_count"] + 1
    else:
        count = 1

    request.session["load_count"] = count

You can then either check the count in view or template to display the captcha.

nemecek_f Thanks. Can you please explain little bit how to integrate it inside my code. somethings like this:

def login_view(request):
     if request.method == 'POST':
            username = request.POST.get('username')
            password =request.POST.get('password')
            user = authenticate(request, username=username, password=password)
            
            if "load_count" in request.session:
                 count = request.session["load_count"] + 1
            else:
                count = 1
                request.session["load_count"] = count
            
            if user is not None:
                   if count <3:
                      login(request, user)
                      messages.add_message(request, messages.INFO,'Login Sucessfull')  
                   if count > 3:
                      #my captcha verification code......
                       login(request, user)
                       messages.add_message(request, messages.INFO,'Login Sucessful
                
            else:
                  messages.info(request, "wrong username or password")

You are on the right track, I am not sure how you plan to integrate catcha though.

The count > 3 should be in the else block I think. Because if you have user, that means the authentication was success.