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

Time:12-30

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 >
      <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 >Sign in</h2>
        <div >
          <div >
            <div >
              <span >
                <span ></span>
              </span>
            </div>
            <input
              type="text"
              
              name="username"
              placeholder="Username"
              required="required"
            />
          </div>
        </div>
        <div >
          <div >
            <div >
              <span >
                <i ></i>
              </span>
            </div>
            <input
              type="password"
              
              name="password"
              placeholder="Password"
              required="required"
            />
          </div>
        </div>
        <div >
          <button type="submit" >
            Sign in
          </button>
        </div>
        <div >
          <a href="{% url 'reset_password' %}" 
            >Forgot Password?</a
          >
        </div>
      </form>
    
      
      <p >
        Don't have an account? <a href="{% url 'register' %}">Register here!</a>
      </p>
    </div>

view.py

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"),
]

CodePudding user response:

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 >{{message}}</div>
{% endfor %}
  • Related