Tag that can be used as ${ tags.csrf_token() }
in mako templates. Remember to import the tags namespace in your template, as such:
<%namespace name="tags" module="my_app.tags"/>
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
- 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
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 <module> import settings # Assumed to be in the same directory. File "/Volumes/opt/projects/django/sutton.git/sutton/settings.py", line 98, in <module> 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?
#
err whoops, posted on the wrong thread! :D
#
Please login first before commenting.