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