Why does the Django message tags boxs is not working?

I have a problems with the message tags. So I have a little apps that send a sms.

When I press the submit button and my webpage, if the sms is send correctly a message.success is printed on the screen.(The success messages work fine. the text and green color appear correclty) But if the message is not sent, an message.error is printed, but only the text is printed, the red color box is not printed(Which is not fine, I also want the Red box to be printed). I searched online to find a answer, but I didn't find anything.THanks for help

views.py

 try:
            sms = Client.messages.create(
                from_="+14509001443",
                body=mess,
                to=number
            )
            send = sms.sid
            print("DOne")
            form.instance.author = request.user
            form.save()
            messages.success(request, f'Votre message a bien été envoyé!')
            return redirect("sms-home")
        except:
            print("error")
            messages.error(request, f'Votre message na pas été envoyé!')
            return redirect("sms-home")

home.html

{% extends "sms/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
    {{ message }}
</div>
{% endfor %}
{% endif %}


<div>
    <form method="POST">
        {% csrf_token %}
        {{ form|crispy }}
        <button class="btn btn-outline-info" type="submit" value="Save">SEND</button>
    </form>
</div>


</body>
</html>
{% endblock content %}

1 answer

  • answered 2020-02-12 23:05 schillingt

    Bootstrap's alert class is alert-danger, I'm pretty sure django's error tag is error. So your alert div is being rendered with the classes "alert alert-error" which doesn't match any styles that are defined.

    To solve this there are a few options:

    1. Generate a generic message with the tag 'danger'.
    2. Customize your bootstrap styles such that alert-error is handled like alert-danger
    3. Add 'danger' as an extra_tag for the messages.error call, then handle the possibility of multiple tags in your template.

    Actually, I wouldn't be suprised if you already need to handle the possibility of multiple tags in your template.