csrf跨站请求伪造解决

前后端任选其一

前端

form表单

<form>
{% csrf_token %}
...
</form>

ajax

data:{csrfmiddlewaretoken:'{{ csrf_token }}'} ( 推荐 )

data:{"csrfmiddlewaretoken":$([name='csrfmiddlewaretoken']").val()}

后端

注释中间件

注释掉csrfmiddleware即可

装饰器 (推荐)

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def func(request):
	pass

使用drf 框架 (推荐)

通过阅读drf的源码,我们可以知道在视图类点点点as_view()方法中开发者已经加了csrf_exempt,这样就可以放心的写一些restful规范的接口给前端调用了。
且看:

urlpatterns = [
    path('', include(router.urls)),
    path('success/',views.SuccessView.as_view())
]
	@classmethod
    def as_view(cls, **initkwargs):
        """
        Store the original class on the view function.

        This allows us to discover information about the view when we do URL
        reverse lookups.  Used for breadcrumb generation.
        """
        if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet):
            def force_evaluation():
                raise RuntimeError(
                    'Do not evaluate the `.queryset` attribute directly, '
                    'as the result will be cached and reused between requests. '
                    'Use `.all()` or call `.get_queryset()` instead.'
                )
            cls.queryset._fetch_all = force_evaluation

        view = super().as_view(**initkwargs)
        view.cls = cls
        view.initkwargs = initkwargs

        # Note: session based authentication is explicitly CSRF validated,
        # all other authentication is CSRF exempt.
        return csrf_exempt(view)

版权声明:本文为General_zy原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。