jinja2 csrf_token extension

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# coding:utf-8
'''
Created on 2009-12-30

@author: Jason Green
@author-email: guileen@gmail.com


in settings.py:
JINJA_EXTS=('jinja2.ext.i18n','youproject.app.extensions.csrf_token',)

use in jinja2 template just like django template:
<form ...>{% csrf_token %}...</form>
'''
from jinja2 import nodes
from jinja2.ext import Extension
from django.utils.safestring import mark_safe
import traceback


class CsrfExtension(Extension):
    # a set of names that trigger the extension.
    tags = set(['csrf_token'])

    def __init__(self, environment):
        self.environment = environment

    def parse(self, parser):
        try:
            token = parser.stream.next()
            return nodes.Output([self.call_method('_render', [nodes.Name('csrf_token','load')])]).set_lineno(token.lineno)

        except:
            traceback.print_exc()

    def _render(self, csrf_token):
        """Helper callback."""
        if csrf_token:
            if csrf_token == 'NOTPROVIDED':
                return mark_safe(u"")
            else:
                return mark_safe(u"<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='%s' /></div>" % (csrf_token))
        else:
            # It's very probable that the token is missing because of
            # misconfiguration, so we raise a warning
            from django.conf import settings
            if settings.DEBUG:
                import warnings
                warnings.warn("A {% csrf_token %} was used in a template, but the context did not provide the value.  This is usually caused by not using RequestContext.")
            return u''

csrf_token=CsrfExtension

More like this

  1. csrf_token for mako by damd 3 years, 11 months ago
  2. Django csrf_token Template Tag Fix by Reustle 3 years, 8 months ago
  3. monkey-patch django to use jinja2 templates for 404/500 pages and 3rd-party apps by brondsem 5 years, 1 month ago
  4. Django 1.2+ template loader for Jinja2 by SimonSapin 3 years, 10 months ago
  5. Add CSRF token to templates by coleifer 2 years, 9 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?

#

(Forgotten your password?)