带有breakline的django + mysql文本字段格式

时间:2012-07-22 17:07:58

标签: mysql django python-2.7

我的MySQL表中有一个text字段。我想使用<br>或模板的某种格式来格式化所有新行。框架内置了什么内容吗?我试着阅读以下页面:

https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs

但似乎该页面不适用于此?有没有我可以参考的文件?谢谢!

3 个答案:

答案 0 :(得分:3)

听起来您需要linebreaksbr模板过滤器。

通常,您可以在模板中使用它:

{{ instance.fieldname|linebreaksbr }}

但是,也可以导入它并在视图中使用它:

from django.template.defaultfilters import linebreaksbr
text_with_br = linebreaksbr(instance.fieldname)

使用linebreaksbr代替编写自己的代码段的好处是,linebreaksbr会为您处理autoescaping

答案 1 :(得分:0)

我决定采用以下方式:"<br />".join(word.split("\n"))。不确定这是否是最好的方式......还在深入挖掘它。它肯定有效!

答案 2 :(得分:0)

根据您的使用情况,这对您来说可能有点过分,但我在管理区域中使用django-tinymce将富文本编辑字段添加到将在模板中使用的字段。这会在数据库和模板中保存html字符串,您可以使用:

{{ model.field|safe }}

输出它而不会丢失html格式。这很容易设置。