0

I'm using DJango to save some html designs in my db. For example here 'Body' has some html content:

enter image description here

When I serialize the content into json, it seems like the html tags get eliminated:

from django.core import serializers

def list_templates(request):
    # retrieve all the templates from the DB
    all_templates = Template.objects.all()
    return HttpResponse(serializers.serialize('json', all_templates))

Here is what I see:

enter image description here

Any recommendations on best practices for saving html codes and their serialization?

1

2 Answers 2

1

I'm not sure why you would store your whole body in the DB but I'm using TinyMCE for storing and editing dynamic HTML. Here's the documentation: readthedocs.io
Just do the following:

# Imports
from django.db import models
from tinymce import models as tinymce_models

#models.py
class MyTemplate(models.Model):
    name = models.CharField(...)
    describe = models.TextField(...)
    body = tinymce_models.HTMLField()

This should give you the desired result without having to serialize data by yourself. You may have to include TinyMCE into your Django-Admin separately.

Sign up to request clarification or add additional context in comments.

Comments

0

Despite Django's ORM that seems me quite hasardous to store code straight as text. I would recommand you use a FileField to save directly the HTML (or whatever extension) file in your DB.

If you need to do it from a textarea input as in a form, read and write the content of the textarea in a .txt or .html file with Python open() function and then store it with a FileField.

1 Comment

May I know why this answer was down-voted and wont fit for you issue ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.