Django LoginView keeps displaying form error messages on refresh

1.6k Views Asked by At

Using Django's built-in LoginView, I want to display an error message on incorrect login. This works fine. However, upon refreshing of the login page, the error message persists.

I want to remove this error message when the user refreshes the page.

urls.py

from django.urls import path
from django.contrib.auth.views import LoginView

urlpatterns = [
    path('login/', LoginView.as_view(template_name='login.html'), name="login"),
]

login.html

{% if form.non_field_errors %}
  <div class="alert alert-danger" role="alert">
    {% for error in form.non_field_errors %}
      <p>{{ error }}</p>
    {% endfor %}
  </div>
{% endif %}

<form method="post" action="{% url 'accounts:login' %}">
            {% csrf_token %}
            <p><input type="text" name="username" autofocus="" required="" id="id_username" placeholder="username"></p>

            <p><input type="password" name="password" required="" id="id_password" placeholder="password"></p>

            <button type="submit" value="Login">Login</button>
            <a id="signup-btn" href="{% url 'accounts:signup' %}"">Don't have an account? Sign up</a>
 </form>

The error message being printed: 'Please enter a correct username and password. Note that both fields may be case-sensitive.'

Any help would be greatly appreciated.

Edit: Sorry for any confusion, I have updated the question to clarify things.

1

There are 1 best solutions below

0
juan pablo Mayorga On

I used your own code, what I did was add a button with the data-dispats attribute to close the bootstrap alert when required, the complete element looked like this:

{% if form.non_field_errors %}
   <div class="alert alert-danger" role="alert">
  <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
        {% for error in form.non_field_errors %}
             <p>{{ error }}</p>
        {% endfor %}
      </div>
 {% endif %}