Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I display Error Messages for the logging funtion in Django?

I am a new Django Developer, and I have some trouble with the login function. My problem is that my system does not show error messages even though it is invalid. I try to enter the wrong username and password, and I expect there are some error messages displayed. However, it does not work. Here is my code:

login_register.html

    <div class="login-form">
      <form action="" method="POST">
        {% csrf_token %}
        {% if form.errors %}
          {% for field in form %}
              {% for error in field.errors %}
                  <p> {{ error }} </p>
              {% endfor %}
          {% endfor %}
        {% endif %}
    
    
        <h2 class="text-center">Sign in</h2>
        <div class="form-group">
          <div class="input-group">
            <div class="input-group-prepend">
              <span class="input-group-text">
                <span class="fa fa-user"></span>
              </span>
            </div>
            <input
              type="text"
              class="form-control"
              name="username"
              placeholder="Username"
              required="required"
            />
          </div>
        </div>
        <div class="form-group">
          <div class="input-group">
            <div class="input-group-prepend">
              <span class="input-group-text">
                <i class="fa fa-lock"></i>
              </span>
            </div>
            <input
              type="password"
              class="form-control"
              name="password"
              placeholder="Password"
              required="required"
            />
          </div>
        </div>
        <div class="form-group">
          <button type="submit" class="btn btn-primary login-btn btn-block">
            Sign in
          </button>
        </div>
        <div class="clearfix">
          <a href="{% url 'reset_password' %}" class="text-center"
            >Forgot Password?</a
          >
        </div>
      </form>
    
      
      <p class="text-center text-muted small">
        Don't have an account? <a href="{% url 'register' %}">Register here!</a>
      </p>
    </div>

view.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def loginUser(request):
    page = 'login'

    if request.user.is_authenticated:
        return redirect('starting-page')

    if request.method == 'POST':
        username = request.POST['username'].lower()
        password = request.POST['password']

        try:
            user = User.objects.get(username=username)
        except:
            messages.error(request, 'Username does not exist')

        user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            return redirect(request.GET['next'] if 'next' in request.GET else 'starting-page')
            # return redirect('starting-page')

        else:
            messages.error(request, 'Username OR password is incorrect')

    return render(request, 'users/login_register.html')

form.py

from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Profile

class CustomUserCreationForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['first_name', 'email', 'username', 'password1', 'password2']
        labels = {
            'first_name': 'Name',
        }

    def __init__(self, *args, **kwargs):
        super(CustomUserCreationForm, self).__init__(*args, **kwargs)

        for name, field in self.fields.items():
            field.widget.attrs.update({'class': 'input'})

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.loginUser, name="login"),
    path('login/', views.loginUser, name="login"),
    path('logout/', views.logoutUser, name="logout"),
    path('register/', views.registerUser, name="register"),
]

I hope you can help me solve the problem. Thank you so much!

>Solution :

Try implementing the below code in your template. If there are any messages that are added in view, will be displayed.

{% for message in messages %}
    <div class="alert alert-info">{{message}}</div>
{% endfor %}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading