Balas
Balas

Reputation: 135

How to pass context variable in a ModelField?

I'm using Django 1.8.

I want to use a CharField with an internal context variable.

For example,

in models.py
...
  content = models.CharField(max_length=200)
...

in template:

...
  {{ model_instance.content }}
...

The output in html:

...
The content of a context variable is {{ request.variable }}
...

But I want to get:

...
The content of a context variable is test-test-test
...

How can I accomlpish it? I used {{ model_instance.content|safe }}, but it had no effect.

Upvotes: 0

Views: 139

Answers (1)

Alex Morozov
Alex Morozov

Reputation: 5993

A simple template tag will do it:

yourapp/templatetags/yourapp_tags.py

from django.template import Template

@register.simple_tag(takes_context=True)
def render(context, content):
    return Template(content).render(context)

yourapp/templates/template.html

{% load yourapp_tags %}
{% render model_instance.content %}

Just make sure your content fields are not writable for plain site users, as it imposes a security risk.

Upvotes: 3

Related Questions