djangodjango-viewsdjango-formsdjango-urlsdjango-authentication

Django - Failed Login Redirecting To Different Page


I am new to Django and I am trying to use the authentication system. I have managed to get it working using the default Auth URLS. (/accounts/login) etc.

I want to get a login form on my homepage so it is always available to unauthenticated users. I have managed to display the form, and when a user enters correct details, the login is successful. Unfortunately when the user enters wrong information it is currently redirecting me to the login url (accounts/login) I have been trying to rectify this, but I either break the auth or it redirects, I cannot seem to find a solution.

Views.py:

def index(request):
    if request.method == 'POST':
        form = AuthenticationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')
    else:
        form = AuthenticationForm()
    return render(request, 'home.html', { 'form': form })

HTML template:

<form class="p-4 p-md-5 border rounded-3 bg-body-tertiary" action="{% url 'login' %}" method="post">
                    {% csrf_token %}

                    <div class="form-floating mb-3">
                        <input class="form-control" id="{{ form.username.id_for_label }}" name="username" type="text" />
                        <label for="{{ form.username.id_for_label }}">{{ form.username.label }}</label>
                    </div>

                    <div class="form-floating mb-3">
                        <input class="form-control" id="{{ form.password.id_for_label }}" name="password" type="password" />
                        <label for="{{ form.password.id_for_label }}">{{ form.password.label }}</label>
                    </div>

                    {% if form.errors %}
                        <div class="justify-content-center d-flex w-75 mt-1 mb-1 alert alert-danger border-0">
                            <small class="text-center mx-4">Your Username and Password Did Not Match!</small>
                        </div>
                    {% endif %}
                    <input class="w-100 btn btn-primary" type="submit" name="submit" value="Login"></input>
                    
                    <a class="text-center pb-3 text-decoration-none" href="{% url 'register' %}"><small class="text-muted">Don't have an account?</small></a>
</form>

urls.py

path('', views.index, name="home"),

I have tried editing the action in the form so it takes me to Home or removing the action altogether however this then breaks the auth.


Solution

  • The problem here is that the AuthenticationForm doesn't handle the authentication logic for you; it is purely a validation form. You have to use Django's authenticate and login functions to handle the login requests directly in your view.

    Updated views.py

    from django.contrib.auth import authenticate, login
    def index(request):
        form = AuthenticationForm(data=request.POST or None)
        
        if request.method == 'POST':
            if form.is_valid():
                username = form.cleaned_data.get('username')
                password = form.cleaned_data.get('password')
                user = authenticate(request, username=username, password=password)
                
                if user is not None:
                    login(request, user)
                    return redirect('/')  # Redirect to home after successful login
            
        return render(request, 'home.html', {'form': form})