[Answered ]-Different content type objects in django template

2👍

✅

The method render you use in get_rendered_html actually does not return a string or anything you can directly use in your template, it returns a HttpResponse object. A HttpResponse object basically consists of the rendered template and Http headers.

from django.template.loader import render_to_string
from django.utils.safestring import mark_safe

class StreamItem(models.Model):
    ...
    def get_rendered_html(self):
        template_name = 'stream_item_%s.html' % self.content_type.name
        return mark_safe(render_to_string(template_name, {'object': self.content_object}))

render_to_string does the same as render, except it returns just a string containing the rendered template, without any header information. mark_safe marks the string as safe for direct use in the template. Without it, any html tags in the string would be escaped upon use in the homepage template.

Leave a comment