Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I embed django csrf token straight into HTML?

within my django app I am storing strings of html in the db that will then be displayed on the users' home pages as "messages". Some of these messages contain forms, but not being written in the template language, I am not able to insert the csrf token (thus breaking the app).

Is there a way to insert this token directly from within the python files i'm editing? i'm looking for something along the lines of:

csrf_token = django.csrf.generate() message = "press the button please: <form><input type='hidden' name='csrf_token' value='%s'><input type='submit' value='press here'></form>" % (csrf_token) 

any other solution that would work in a similar scenario would be great. Thanks

Edit: Actually that's not going to work because 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?

like image 951
ergelo Avatar asked Jul 20 '10 12:07

ergelo


People also ask

Where do I put CSRF token in HTML?

For additional safety, the field containing the CSRF token should be placed as early as possible within the HTML document, ideally before any non-hidden input fields and before any locations where user-controllable data is embedded within the HTML.

How does CSRF token work in Django?

Django has a {% csrf_token %} tag that is implemented to avoid malicious attacks. It generates a token on the server-side when rendering the page and makes sure to cross-check this token for any requests coming back in. If the incoming requests do not contain the token, they are not executed.

What is CsrfViewMiddleware?

A CSRF cookie that is a random secret value, which other sites will not have access to. CsrfViewMiddleware sends this cookie with the response whenever django. middleware.


1 Answers

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

like image 54
viam0Zah Avatar answered Sep 29 '22 02:09

viam0Zah