How can I embed django csrf token straight into HTML?
Asked Answered
B

3

44

Is there a way to insert the the csrf token directly from within the Python files I'm editing? The token is different for each session, so storing it in the DB is not very useful. Is there a way to dynamically load the token within the view?

Blare answered 20/7, 2010 at 12:27 Comment(0)
A
56

Call django.middleware.csrf.get_token(request) to get the CSRF token.

Av answered 21/7, 2010 at 12:49 Comment(2)
Does this work by putting the token into a hidden input? Because I keep getting the same error, what would be the best way to put this token into the form?Glyconeogenesis
Okay solution for me was to use name "csrfmiddlewaretoken" instead of "csrf_token"Glyconeogenesis
G
52

The way to use it, is to use it directly in the templates.

From the documentation,:

<form action="" method="post">
{% csrf_token %}

is all you have to include.

Guimar answered 20/7, 2010 at 15:22 Comment(3)
thanks. the problem is that the 'message' is created in a view, and stored into the db without ever going through a view. I'll solve the problem by turning the form button into a link and going through a view to bypass the csrf.Blare
the question is for the case where you dont use django's templatesCatalonia
This solved it for me during the installation of Django-CMS! For some reason it would not login without this token in the only template I had. Weird.Arginine
K
11

The accepted answer assumes that token is already set in the request object.

Maybe something like this is better:

from django.middleware import csrf
def get_or_create_csrf_token(request):
    token = request.META.get('CSRF_COOKIE', None)
    if token is None:
        token = csrf._get_new_csrf_key()
        request.META['CSRF_COOKIE'] = token
    request.META['CSRF_COOKIE_USED'] = True
    return token
Karim answered 13/9, 2013 at 8:44 Comment(2)
you should not use internal APIs and in fact _get_new_csrf_key() does not exist in Django anymore. you should use get_token().Civet
csrf.get_token already creates a new token if it doesn't exists yetAnchorite

© 2022 - 2024 — McMap. All rights reserved.