简体   繁体   中英

No HTML output to blog post with Django

I've installed the app TinyMCE and all is up and running. There's one problem though. When posting the HTML input with an image is displayed in plain text.

 <p><img src="https://www.djangoproject.com/s/img/logos/django-logo-negative.png" alt="django" /></p> <p>Lorem ipsum dolor sit amet, inani clita efficiantur sed et, ad honestatis complectitur vim.</p> 

index.html:

{% for post in posts %}
          <div class="post">
          <h2>{{ post.title }}</h2>
          <p>Posted on {{ post.timestamp }} by {{ post.author }}</p>
          <p>{{ post.bodytext }}</p>
          </div>
      {% endfor %}

models.py:

from django.db import models
from django.utils import timezone
from django.conf import settings
from tinymce.models import HTMLField

class posts(models.Model):
    author = models.CharField(max_length = 30)
    title = models.CharField(max_length = 100)
    bodytext = HTMLField()
    timestamp = models.DateTimeField(default = timezone.now) # sets a default date & time value when creating a new post

    class Meta:
        verbose_name_plural = "posts" # sets the plural name of posts (default = postss)
    def __str__(self):
        return self.title

I guess there's something I have forgotten to do. So what is wrong here?

It's because the html is being escaped. For example if you let anonymous users post articles (or comments for example) on your site, and let them write their own html (and thus javascript), bad things can happen.

If it's just you writing the Posts, feel free to use:

{{ post.bodytext|safe }}

More info about this here:

https://docs.djangoproject.com/en/1.8/ref/templates/language/#automatic-html-escaping

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM