How can I add an error message in my login form

Hello everyone,

I’ve been working on implementing error message handling in my login form for authentication failures. After some research, I managed to write code that displays all messages generated by the system. However, I encountered an issue where I only wanted to display the last message rather than the entire list of messages.

<form action="{% url 'users:user_add' %}" method="post">
    {% csrf_token %}
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" required><br>

    <label for="password">Password:</label>
    <input type="password" id="password" name="password" required><br>

    <label for="email">email:</label>
    <input type="email" id="email" name="email" required><br>

    <button type="submit">Add User</button>
</form>

{% if messages %}
<ul class="messages">
    {% for message in messages %}
        <li class="{{ message.tags }}">{{ message }}</li>
    {% endfor %}
</ul>

{% endif %}

To address this, I created a function to extract and render only the last message alongside the page rendering process. While this approach technically works, I found it to be less efficient compared to utilizing Django’s built-in messages framework.

def user_add(request):
user_type = request.session.get(‘user_type’)
if user_type != ‘Admin’:
return redirect(reverse(‘users:login_view’))

if request.method == 'POST':
    username = request.POST.get('username')
    password = request.POST.get('password')
    email = request.POST.get('email')

    new_user = CustomUser.create_user(username=username, password=password, email=email, user_type="moderator")

    if new_user == "user exist":
        message = "This User already exist"
        return render(request, 'users/user_add.html', {'message' : message}) 
    
    else:
        log_message = f"New User created '{new_user.username}'."
        logger.info(log_message)

    messages.success(request, 'User created successfully.')
    return redirect(reverse('users:users_list'))

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

I’ve attempted to search for solutions on how to retrieve the last inserted message or obtain all messages from the messages framework, but I haven’t had much success. If anyone has insights or suggestions on how to achieve this, I would greatly appreciate your assistance. Thank you in advance for your help.

Welcome @Domenez25 !

Normally, form errors are rendered with the form - you don’t log errors as “Messages” to be rendered with the message framework. Django is designed such that form and form field-related errors are rendered when you rerender a form after it as failed your validation tests for the form.

Review the docs at Using forms to validate data and How errors are displayed to see how to properly handle form-related errors.