How can I embed django csrf token straight into HTML?

前端 未结 3 1879
一个人的身影
一个人的身影 2021-01-31 08:46

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

相关标签:
3条回答
  • 2021-01-31 09:17

    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
    
    0 讨论(0)
  • 2021-01-31 09:19

    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.

    0 讨论(0)
  • 2021-01-31 09:31

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

    0 讨论(0)
提交回复
热议问题