Search code examples
pythondjango-modelsdjango-templatesdjango-viewsdjango-jsonfield

How to render characters in a textfield correctly in a JSON template


I have created a Django application with a model with a TextField. When I use the admin interface, I can populate the TextField as such below:

Admin interface with TextField

However, when I render it in JSON using a template I get the following on my browser. I.e. it cannot handle the line breaks correctly as such:

Web browser with rendered JSON

I am not sure how to handle this correctly, so that the text from my text field can be typed as required within the admin interface, and then rendered correctly as JSON.

Here is a snippet from my model.py:

@python_2_unicode_compatible
class Venue(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=50, blank=False, null=False)
    description = models.TextField(blank=False, null=False)
    def __str__(self):
        return self.name

Here is the function in the views.py

def venues(request):
    venues_list = Venue.objects.order_by('-name')
    context = {'venues_list':venues_list}
    return render(request, 'myapp/venues.json', context, content_type='application/json')

Here is my venue.json template:

[
    {% for venue in venues_list %}
        {
            "venue_id":"{{venue.id}}",
            "name":"{{venue.name}}",
            "description":"{{venue.description}}"
        }
        {% if forloop.last %}{% else %}, {% endif %}
    {% endfor %}
]

Any help appreciated?

P.S. Not sure if a template is a good approach. But I want to control what fields get displayed in the JSON data, not just JSON dump the entire model.


Solution

  • I managed to do it... So after further reading, I decided that using a template wasn't the best approach for rendering JSON data. I found I could use JsonResponse to handle the displaying of the JSON data correctly.

    So here I have deleted my template and re-wrote my function in views.py to look like this.

    from django.http import JsonResponse ...

    def venues(request):
        venues_list = Venue.objects.order_by('-name')
        venue_array =[]
    
        for venue in venues_list:
            record = {"venue_id":venue.id, "name":venue.name, "description":venue.description}
                venue_array.append(record)
    
        return JsonResponse(venue_array, safe=False)
    

    All now works fine, as my JSON displays correctly with the appropriate line breaks.