How can I embed django csrf token straight into HTML?

巧了我就是萌 提交于 2019-12-20 09:12:47

问题


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:


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




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/3289860/how-can-i-embed-django-csrf-token-straight-into-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!