【问题标题】:CSRF verification failed. Request aborted. Django 1.9 [duplicate]CSRF 验证失败。请求中止。 Django 1.9 [重复]
【发布时间】:2018-03-14 07:29:49
【问题描述】:

我刚刚开始在我的项目上实现发布请求,但我在使用 csrf 令牌时遇到了问题。

即使看起来我使用正确(我使用渲染,启用 cookie,{% csrf_token %} 在 html 代码中,并且我在 django 设置中有中间件)

编辑: 全视图.py:

def mouvementCreation(request):
    idMI = 0
    especes = TbEspece.objects.order_by('id')
    #Get Mouvement informations

    #Connection to 'erp-site' DB 
    cursor = connections['erp-site'].cursor()
    try:
        #Get Produits list from Espece
        query = "{CALL SP_webGET_PRODUIT_FROM_ESPECE(%s,%s,%s,%s,%s)}"
        arguments = (2016, 'C', 0, 10, 'A',)
        cursor.execute(query, arguments)
        produits = dictfetchall(cursor)

        #Get Transporters list
        cursor.execute("{CALL SP_webGET_TRANSPORT}")
        transporters = dictfetchall(cursor)

        #Get Livreur list
        cursor.execute("{CALL SP_webGET_LIVREUR}")
        livreurs = dictfetchall(cursor)
    finally:
        cursor.close()       

    cursor = connections['site'].cursor()
    try:
        #Get Circuit list
        cursor.execute("{CALL SP_webGET_CIRCUIT_FOR_MVT}")
        circuits = dictfetchall(cursor)

        #Get Source list
        cursor.execute("{CALL SP_webGET_SOURCE_FOR_MVT}")
        mvtsources = dictfetchall(cursor)

        #Get Dest list
        cursor.execute("{CALL SP_webGET_DEST_FOR_MVT}")
        destinations = dictfetchall(cursor)

        #Get PontBascule list
        cursor.execute("{CALL SP_webGET_PBASCULE}")
        pontBascules = dictfetchall(cursor)
    finally:
        cursor.close()

    reg_normes = TbRegauxnormes.objects.all()
    ordreexecs = TbOrdreexecution.objects.all()
    form = mouvementForm(request.POST or None)
    if form.is_valid():
        pont = form.cleaned_data['pont']
        dateheure = form.cleaned_data['dateheure']
        poid = form.cleaned_data['poid']
        dsd = form.cleaned_data['dsd']
        typepesee = form.cleaned_data['typepesee']
        #Connection to 'erp-site' DB 
        cursor = connections['pontbascule'].cursor()
        try:
            #Get Produits list from Espece
            query = "{CALL SP_ADD_MANUAL_PESEE(%s,%s,%s,%s,%s, %s,%s,%s,%s,%s, %s,%s,%s,%s,%s, %s,%s,%s,%s,%s, %s,%s,%s)}"
            arguments = (pont, 'TICKETCHEAT', dateheure, poid, dsd,typepesee, '','','','','','','','','','','','','','','','','')
            cursor.execute(query, arguments)
        finally:
            cursor.close()  
    return render(request, 'mouvementCreation.html', {'form': form, 'especes' : especes, 'produits' : produits, 'transporters' :  transporters, 'livreurs' : livreurs, 'circuits' : circuits, 'mvtsources' : mvtsources, 'destinations' : destinations, 'pontBascules' : pontBascules} )

模板:

<form name="Form1" method="post" action="" enctype="text/plain" id="Form1">
{% csrf_token %}
<input type="text" id="Editbox9" style="position:absolute;left:87px;top:46px;width:86px;height:16px;line-height:16px;z-index:173;" name="pont" value="" spellcheck="false">
<input type="text" id="Editbox34" style="position:absolute;left:87px;top:80px;width:86px;height:16px;line-height:16px;z-index:174;" name="dateheure" value="" spellcheck="false">
<input type="text" id="Editbox35" style="position:absolute;left:87px;top:114px;width:87px;height:16px;line-height:16px;z-index:175;" name="poid" value="" spellcheck="false">
<input type="text" id="Editbox36" style="position:absolute;left:88px;top:153px;width:84px;height:16px;line-height:16px;z-index:176;" name="dsd" value="" spellcheck="false">
<input type="text" id="Editbox37" style="position:absolute;left:87px;top:187px;width:86px;height:16px;line-height:16px;z-index:177;" name="typepesee" value="" spellcheck="false">
<input type="submit" id="Button14" name="submit" value="Submit" style="position:absolute;left:361px;top:65px;width:96px;height:25px;z-index:178;">
</form>

中间件设置:

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

我搜索了多个帖子并尝试了很多修复,但到目前为止没有任何效果,我仍然收到“失败原因:CSRF 令牌丢失或不正确。”

【问题讨论】:

  • 您是否使用同一个视图mouvementCreation 来显示表单并处理发布的数据?令牌是否出现在呈现的 html 中(在浏览器中查看源代码以检查)?。
  • 当我在浏览器中检查源时,令牌确实出现了。是的,理想情况下我想做的是从视图中的表单中获取信息,然后在我的数据库中调用一个存储过程来创建一个新条目
  • 啊,我觉得问题出在enctype="text/plain"。见this question。
  • 是的,这确实是问题所在,非常感谢。我也想知道,因为正如您在我的视图中看到的那样,我在收到表单后调用了一个存储过程,但该过程似乎从未触发(我单独测试过的过程工作)
  • 抱歉,这是一个单独的问题,所以我无能为力。

标签: python django django-forms django-csrf


【解决方案1】:

您必须将请求上下文传递给模板。

【讨论】:

  • 什么意思?
  • 最初我认为这是问题所在。但是您正在使用渲染()。渲染已通过内置请求上下文。这个答案是不正确的。你为什么要通过 locals() ?代替本地人,您可以将表单实例和其他上下文作为 dict 传递吗?
  • 我使用的是本地人,因为在我正在关注表单的教程中使用了本地人,你如何传递表单实例?
  • 返回渲染(request, 'mouvementCreation.html', {'form': form})
  • 我试过了,但遗憾的是它似乎没有太大变化
【解决方案2】:

将此添加到您的views.py

@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
    return super(GetOrderCount, self).dispatch(request, *args, **kwargs)

【讨论】:

  • 如果我不知道如何让他能够解析@method_decorator 或 GetOrderCount,Django 似乎不知道这些调用
  • Getordercounts 应该是您的班级名称。并从 django.core.context_processors import csrf 导入
  • 它似乎适用于类部分,但没有使用导入,不应该是 (csrf) 而不是 (csrf_exempt) 吗?
  • 我找到了导入使其工作,但它不能解决我的 csrf 问题
【解决方案3】:

我暂时解决了这个问题,我不得不评论“#'django.middleware.csrf.CsrfViewMiddleware'” 为了使 csrf 工作,必须这样做似乎很奇怪,但至少它可以工作。

【讨论】:

  • 这不是一个理想的解决方案。通过注释掉 CsrfViewMiddleware,您将禁用整个站点的 CSRF 保护。
  • 我明白这一点,但至少我可以在找到修复程序的同时解决它,您知道是什么原因造成的吗?
猜你喜欢
  • 2016-05-29
  • 2012-12-07
  • 2015-03-08
  • 1970-01-01
  • 2014-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多