【问题标题】:How to access the csrf_token inside django view如何在 django 视图中访问 c​​srf_token
【发布时间】:2021-04-27 15:44:35
【问题描述】:

我正在尝试访问 django 视图函数中的 csrf_token。

我已尝试导入 csrf:

from django.template.context_processors import csrf

并像这样使用它

landingPageHtml = landingPageHtml.replace('csrf_token', csrf(request)['csrf_token'])

但我遇到了一个错误。第二个参数必须是 str 而不是惰性对象。

如何在视图中访问 c​​srf 令牌?

@login_required
def viewLandingPage(request, slug):

    lp = getLandingPage(request, slug)

    landingPageHtml = getLandingPageFile(request, lp['file'])

    landingPageHtml = landingPageHtml.replace(
        '{{ lp.seo_title }}', lp['seo_title'])

    landingPageHtml = landingPageHtml.replace(
        '{{ lp.seo_description }}', lp['seo_description'])

    landingPageHtml = landingPageHtml.replace('csrf_token', 'csrf_token')

    return HttpResponse(landingPageHtml)

【问题讨论】:

标签: python django django-csrf csrf-token


【解决方案1】:

也许你正在寻找这个来获取 csrf 令牌

django.middleware.csrf.get_token(request)

参考:How can i get csrftoken in view?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 2020-11-09
    • 2019-06-01
    相关资源
    最近更新 更多