| 1 | from django import template |
| 2 | |
| 3 | register = template.Library() |
| 4 | |
| 5 | class CsrfTokenNode(template.Node): |
| 6 | def __init__(self, useid=True): |
| 7 | self.useid = useid |
| 8 | |
| 9 | def render(self, context): |
| 10 | csrf_token = context.get('csrf_token') |
| 11 | if csrf_token: |
| 12 | return ('<div style="display:none;">' |
| 13 | '<input type="hidden" %s' |
| 14 | 'name="csrfmiddlewaretoken" value="%s" /></div>' |
| 15 | ) % (self.useid and 'id="csrfmiddlewaretoken" ' or '', csrf_token) |
| 16 | else: |
| 17 | return '' |
| 18 | |
| 19 | @register.tag |
| 20 | def csrf_token(parser, token): |
| 21 | args = token.contents.split() |
| 22 | |
| 23 | if u'noid' in args[1:] or hasattr(parser, '_csrf_used'): |
| 24 | return CsrfTokenNode(False) |
| 25 | else: |
| 26 | parser._csrf_used = True |
| 27 | return CsrfTokenNode() |