I am using CKEditor to enter text and saving into database. When I retrieve it description, it also shows the html p tags which i dont want. How can I save it into database such that the p tags don't show but tags like are still applied. Essentially I want to save it as html itself and not text. Is there a way I can do that? Currently I am using TextField to store the description.
CodePudding user response:
You can override the save method of model . for example whenever the object gets created or update . you just Replace the
Tag Using regex and and can also extra tags with regex .
Example:
def save(instance):
instance.html = instance.html.replace("<p>","<div>").replace("</p>","</div>")
You can also use regex instead of replace function .
- You can also save this output of replace or regex into another field and show that chaned html content on the website
CodePudding user response:
You should use a HTMLField [Django-doc] for this: from django.db import models
class MyModel(models.Model): description = models.HTMLField() This will store the HTML in the database, and render it as HTML when you retrieve the object. Normally a HTMLField will sanitize the HTML to prevent XSS attacks, but you can disable this with the: description = models.HTMLField(sanitize=False) in case you want to allow arbitrary HTML. Note that a HTMLField is a TextField under the hood, it just uses a special form widget (AdminHTMLWidget [GitHub]) and serialization in the ORM layer.