views:

149

answers:

2

Hi,

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?

+1  A: 

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.

Lakshman Prasad
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.
ergelo
A: 

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

Török Gábor
that would've solved it. thanks for pointing it out!
ergelo