Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing and escaping Django tags and filters in Django models

I am outputting content from my models to my templates, however some model fields call data stored in other models. This happens only in a few fields. I am wondering whether using an if tag to evaluate this would be more efficient compared to storing the django tags inside the models.

Answers to this question say that storing django tags in models is a bad idea without giving reasons (although I think one of the reasons may be someone else may inject some tags in the Database). Assuming that database injection is a rarity, is there a way of escaping Django tags and filters stored in a model.

Or better yet, what would be the most efficient method to handle the above situation where one model field in several fields calls fields stored in another model.

Example:

This should be stored in my models

<p>We focus on:</p>
{% for item in services %}
{% url service_view item.id as service_url %}
<ul>
<li><a href="service_url">{{item.title}}</a></li>
</ul>
{% endfor %}

Outputting it should result in django parsing the relevant django tags as if part of the template

like image 497
Dennis Kioko Avatar asked Nov 14 '22 08:11

Dennis Kioko


1 Answers

Thanks Ned, I tried implementing that but I found it to be quite complex and its also disadvantageous in terms of portability.

However, I found exactly what I needed at Django Snippets (dont know why I didn't look there first). Its a quite useful utility known as render_as_template.

After setting it up as a custom tag, all that I needed was to use it in the form {% render_as_template about_view.content %} and the tags in the models were rendered as models.

Instructions on creating your own custom templates and tags available here

like image 148
Dennis Kioko Avatar answered Nov 17 '22 06:11

Dennis Kioko