pythondjangodjango-messages

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


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!


Solution

  • {% 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 %}