Troubleshooting error when using markdown filter in Django template

孤街浪徒 提交于 2019-12-03 13:54:57

问题


When using the Markdown libraries I seem to get the following error:

Error in 'markdown' filter: Django does not support versions of the Python markdown library < 2.1.

As an example, it occurs on a tag such as:

{{ticket.get_description|markdown:"safe,footnotes,tables"}}

The get_description function is defined in the Ticket model. We've upgraded to Django 1.5 recently and the code was written pre Django 1.4. I've also upgraded the Markup library to 2.3.1 but the problem still persists. I've also cleared old .pyc files, just to be sure.

From what I've read, the django.contrib.markup libraries have been deprecated. So, what would the suggested solution/alternative be?


回答1:


one idea is to install markdown2 library of python see here then you create your decorator

import markdown2
.. all other imports needed..

register = template.Library()

@register.filter(is_safe=True)
@stringfilter
def markdown2(value):
    return mark_safe(markdown2.markdown(force_unicode(value),safe_mode=True,enable_attributes=False))

then you use it

{% load myapp_markup %}
{{ value|markdown2 }}

code is adpated (and not tested) from here




回答2:


Just an update:

My decorator looks like this:

import markdown2
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe

register = template.Library()

@register.filter(is_safe=True)
@stringfilter
def convertTxt(value):
    return mark_safe(markdown2.markdown(force_unicode(value)))

register.filter('convertTxt', convertTxt)

Also, I've noticed that it is not prudent to name your module or your method markdown2 :)



来源:https://stackoverflow.com/questions/16689334/troubleshooting-error-when-using-markdown-filter-in-django-template

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