Login

jinja2 csrf_token extension

Author:
jasongreen
Posted:
December 30, 2009
Language:
Python
Version:
1.1
Score:
0 (after 0 ratings)

init env

env = Envoriment(extensions=('youproject.app.extensions.csrf_token'), loader=loader)

or see [http://www.djangosnippets.org/snippets/1844/] and in settings.py:

JINJA_EXTS=('jinja2.ext.i18n','youproject.app.extensions.csrf_token',)

use this extension in jinja2 template just like django template:

<form ...>{% csrf_token %}...</form>

 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: [email protected]


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. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks 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?

#

Please login first before commenting.