csrf_token for mako

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def csrf_token(context):
    csrf_token = context.get('csrf_token', '')
    if csrf_token == 'NOTPROVIDED':
        return ''
    return u'<div style="display:none"><input type="hidden" name="csrfmiddlewaretoken" value="%s" /></div>' % (csrf_token)

# In your mako rendering function, whichever that is,
# add "csrf_token" to the context as such:

def render_mako(request, view_name, template_name, **kwargs):
    """
    Renders the template given the name of it and the request to add the request
    to the context.
    """
    from django.core.context_processors import csrf

    # ...
    kwargs['csrf_token'] = csrf(request)['csrf_token']
    # ...

More like this

  1. Django csrf_token Template Tag Fix by Reustle 3 years, 8 months ago
  2. Add CSRF token to templates by coleifer 2 years, 9 months ago
  3. Test Integration for mako templates by eriklee 5 years, 5 months ago
  4. intergrate mako and genshi with django by huangyi 7 years, 1 month ago
  5. jinja2 csrf_token extension by jasongreen 4 years, 3 months ago

Comments

tickletik (on May 26, 2010):

I'm trying to install this in my project but its not working. I'll give all relevent information.

First in settings.py I have: from jinja2 import Environment env = Environment(extensions=['jinja2.ext.i18n', 'extensions.csrf_token'])

I have csrf token saved in a file in an app on the PYTHONPATH called extensions/csrf_token.py

Next I get this error when I run python manage.py shell:

Traceback (most recent call last): File "manage.py", line 4, in [HTML_REMOVED] import settings # Assumed to be in the same directory. File "/Volumes/opt/projects/django/sutton.git/sutton/settings.py", line 98, in [HTML_REMOVED] env = Environment(extensions=['jinja2.ext.i18n', 'extensions.csrf_token']) File "/Volumes/opt/download/_python/_django/jinja2/jinja2/environment.py", line 278, in init self.extensions = load_extensions(self, extensions) File "/Volumes/opt/download/_python/_django/jinja2/jinja2/environment.py", line 76, in load_extensions result[extension.identifier] = extension(environment) TypeError: 'module' object is not callable

I've also tried just using JINJA_EXTS=('extensions.csrf_token') but when I try using {%csrf_token%} in my template I get:

Exception Type: TemplateSyntaxError Exception Value:

Encountered unknown tag 'csrf_token'. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block'.

The app in which csrf_token.py is located, "extensions" is loaded up in INSTALLED_APPS

Can someone please help me?

#

tickletik (on May 26, 2010):

err whoops, posted on the wrong thread! :D

#

(Forgotten your password?)