在 Wagtail 页面上禁用 CSRF 验证

Disable CSRF validation on Wagtail Page

我正在尝试在 wagtail 页面上执行 curl POST 请求。不幸的是我遇到了 CSRF 保护。

我尝试使用 @csrf_exempt 装饰器在这种特定类型的页面上禁用 CSRF,但没有成功。

这是我的伪代码(许多尝试之一):

@method_decorator(csrf_exempt, name='serve')
class NewsletterPage(MedorPage):

    class Meta:
        verbose_name = _("newsletter page")

似乎 csrf 验证甚至在调用 serve 方法之前就完成了。

有什么想法吗?

谢谢

您必须装饰 wagtail.core.views.serve 视图本身。由于这是不完整的,因为您想将其 url 保留在 wagtail_urls 中,您可以在包含 wagtail urls 的任何地方执行以下操作:

# urls.py

# ...
from wagtail.core import urls as wagtail_urls
# ...


### these two lines can really go anywhere ...
from wagtail.core import views
views.serve.csrf_exempt = True
### ... where they are executed at loading time

urlpatterns = [
    # ...
    re_path(r'^pages/', include(wagtail_urls)),
    # ...
]

届时这将适用于所有鹡鸰页面,而不仅仅是一种特定类型。

我最终像这样子类化了 CSRF 中间件:

from django.middleware.csrf import CsrfViewMiddleware

from wagtail.core.views import serve

from myproject_newsletter.models import NewsletterIndexPage


class CustomCsrfViewMiddleware(CsrfViewMiddleware):

    def process_view(self, request, callback, callback_args, callback_kwargs):

        if callback == serve:
            # We are visiting a wagtail page. Check if this is a NewsletterPage
            # and if so, do not perfom any CSRF validation
            page = NewsletterIndexPage.objects.first()
            path = callback_args[0]

            if page and path.startswith(page.get_url_parts()[-1][1:])
                return None

        return super().process_view(request, callback, callback_args, callback_kwargs)