3

So I want to make a blog post with HTML formatting from the admin page directly. For example from the models.py, you see the description is a TextField. When I go to the admin page to make a blog post, I want to be able to add HTML tags to my blog. So the text field will have HTML content. While I call the blog post onto the HTML template I want it to read the description as a HTML file and not just a text field.

models.py

from django.db import models

class Blog(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    date = models.DateField()

Blog.description at admin page

<HTML>
<body>
<p>Welcome to my first blog post!!</p>
</body>
</html>

blog.html

  <h1>{{ blog.title }}</h1>
  <hr>
  <p>{{ blog.description }}</p>

Any help is appreciated. Thanks!

  • Maybe you can make use of javascript and then create those html tags ? If I am not wrong, right now in html, it is coming as string over there or not rendering ? – Shashank Aug 16 '20 at 20:14
  • yup, it's coming as a string. I don't know javascript tho :/. would that be possible? – Rohit Manjunath Aug 16 '20 at 20:15
  • Can you try this: https://stackoverflow.com/a/12416289/3523510 I think it is answered :) – Shashank Aug 16 '20 at 20:18

1 Answers1

7

You can render it with the |safe template filter [Django-doc]. This will disable escaping HTML fragments, and it will thus no longer convert < to &lt; for example:

<h1>{{ blog.title|safe }}</h1>
  <hr>
  <p>{{ blog.description|safe }}</p>

You however might want to take a look at the django-ckeditor package [GitHub] which offers a dedicated field, widget, etc. to enable editing the text with respect to rendering.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555