898247
898247

Reputation: 10606

TypeError using custom template tag

I get 'module' object is not callable using the following template tag:

projectname/controlpanel/templatetags/__init__.py (blank file)

projectname/controlpanel/templatetags/md_to_html.py

from django import template
from markdown import markdown

register = template.Library()


@register.filter(name='to_html')
def to_html(md):
    return markdown(md)

In one of my views, I return {'campaign': campaign}, with campaign being an instance of a model with a description TextField.

<div class="span8" id="editor2">
   {{ selected_campaign.description|to_html }}
</div>

Upvotes: 0

Views: 655

Answers (2)

suhailvs
suhailvs

Reputation: 21680

add this to INSTALLED_APPS

'django.contrib.markup',

copy markdown(http://pypi.python.org/pypi/Markdown) to your django project directory

then use

{% load markup %}
<div class="span8" id="editor2">
      {{ selected_campaign.description|markdown:"safe" }}
</div>

Update:

django.contrib.markup is deprecated in Django 1.5. Here is a simple replacement for the markdown filter.

remove line 'django.contrib.markup', from INSTALLED_APPS

steps to create a template tag:

  • add a folder templatetags in any of your app folder.
  • inside templatetags folder add an empty file __init__.py

add markup.py inside templatetags with these codes:

from django import template
from django.utils.safestring import mark_safe
import markdown as mkdn

register = template.Library()     
@register.filter
def markdown(value,smode=None):
    return mark_safe(mkdn.markdown(value, safe_mode='escape'))

Upvotes: 1

Victor Castillo Torres
Victor Castillo Torres

Reputation: 10811

Well I do not why but markdown seems does not work inside a function in django for example I typed this in django shell (python manage.py shell):

from markdown import markdown

def yes():
     return markdown("YES")

and it gives me the next error:

NameError: global name 'markdown' is not defined

and this seems to work

def yes():
     from markdown import markdown
     return markdown("YES")

outside django shell the first method works correctly hope this helps!

Upvotes: 0

Related Questions