[Django]-How to send Json or "dict" using Django Messages Framework

3๐Ÿ‘

โœ…

{% for message in messages %}
    <p>{{ message.tags }}</p>
    {% if message.tags == 'available_ids error' %}
    {% for obj,values in message.message.items %}
        <div>
            {{ obj  }} 
            {% for val in values %}
                <p class="user-id">{{ val }}</p>
            {% endfor %}
        </div>
    {% endfor %}
    {% endif %}
{% endfor %}

You can use above code snippet inside template to make it working and modify it according to your requirements.

How it works?

We iterate through each and every message, as we have inserted dictionary in messages so we have to iterate dictionary and inside dictionary we have list so we have to iterate that too.
Therefore we have to use three for loop.
You have to apply some conditions like when you have to iterate? You can check using this by tags.

Here I have hard coded (iterating condition) for this purpose.

Edit:

Using two for loops
Update your clean_X with these lines

available_now = ["example","hello","ahc","sdcsd"]
messages.error(self.request, message = available_now,extra_tags="available_ids")

and use these lines in templates

{% for message in messages %}
    <p>{{ message.tags }}</p>
    {% if message.tags == 'available_ids error' %}
        <div>
            {% for val in message.message %}
                <p class="user-id">{{ val }}</p>
            {% endfor %}
        </div>
    {% endif %}
{% endfor %}
๐Ÿ‘คsonus21

0๐Ÿ‘

In views.py

def account_exists(request):

    error_message = {"for": "register", "type": "error", "msg": "Something wrong here, it may be that you already have an Account!"}
    messages.error(request, error_message)

    return redirect("register")

HTML

<div>
    {% for message in messages %}
    <script>
        message = "{{ message | safe}}"
        message = message.replace(/'/g, '"')
        console.log(message, typeof (message))
        json_message = JSON.parse(message)
        console.log(json_message, typeof (json_message))
        console.log(json_message.for)
        console.log(json_message.type)
        console.log(json_message.msg)
    </script>
    <br>
    {% endfor %}
</div>
๐Ÿ‘คUdesh

Leave a comment