How to send Json or "dict" using Django Messages Framework

Question:

I’m using Django Messaging framework to send additional data on the validation error:

def clean_X(self):
        xuser_id = self.cleaned_data['xuser_id']
        if xuser.objects.filter(xuser_id=xuser_id).exists():
            available_now = {"available" : ["example","hello","ahc","sdcsd"]}
            messages.error(self.request, message = available_now,extra_tags="available_ids")
            raise forms.ValidationError('Sorry! User ID "%(xuser_id)s" is already taken, Please try another or chose one from following:', params={"xuser_id" : xuser_id})
        return xuser_id 

The message is converted as a string when tried to access in the template: like

"{"available" : ["example","hello","ahc","sdcsd"]}"

making difficult to access programmatically i.e message.available

How can i send a json directly to the template using Django-Messages. My intention is here, not just to display a message rather make available-id‘s clickable (like the one in gmail auto-suggestion of username)

Thanks!

Asked By: Satish V Madala

||

Answers:

{% 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 %}
Answered By: sonus21

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>
Answered By: devp
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.