如何在direct_to_template上免除CSRF保护

sha*_*eel 32 django csrf

我在我的django应用程序中有一个流程,我将用户重定向到另一个服务(例如PayPal),该服务经过一些自己的处理后,将用户返回到我自己的服务器上.我的服务器上的返回点是一个简单的HTML成功页面,我使用direct_to_template进行渲染.

由于某些奇怪的原因,另一个服务器发送POST请求,因此用户看到CSRF令牌丢失错误,因为另一个服务器不发回任何CSRF令牌.

如何从CSRF令牌中免除direct_to_template视图?

Ala*_*air 57

您可以使用csrf_exempt装饰器禁用特定视图的CSRF保护.

说你的网址模式是:

('^my_page/$', direct_to_template, {'template': 'my_page.html'})
Run Code Online (Sandbox Code Playgroud)

将以下导入添加到您的urls.py:

from django.views.decorators.csrf import csrf_exempt
Run Code Online (Sandbox Code Playgroud)

然后将网址格式更改为:

('^my_page/$', csrf_exempt(direct_to_template), {'template': 'my_page.html'})
Run Code Online (Sandbox Code Playgroud)


Nee*_*rma 50

您可以使用@csrf_exempt装饰器来排除csrf令牌,因为您必须导入

from django.views.decorators.csrf import csrf_exempt
Run Code Online (Sandbox Code Playgroud)

然后@csrf_exempt在你的观点前写

这将正常工作:)

  • 这根本不回答这个问题,因为他想使用内置的direct_to_template函数,而不是装饰自己的观点 (3认同)
  • 您还可以在`dispatch`方法中使用`@method_decorator(csrf_exempt)`来获取基于类的视图。 (2认同)