Storing and escaping Django tags and filters in Django models

风流意气都作罢 提交于 2019-12-23 10:26:07

问题


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


回答1:


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




回答2:


django-dbtemplates probably comes close to doing what you want.




回答3:


You should be using inclusion tags and then include that tag wherever you'd like the html to be rendered. The model should just be generating values for the variables, not formatting.



来源:https://stackoverflow.com/questions/3594909/storing-and-escaping-django-tags-and-filters-in-django-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!