【发布时间】:2018-04-12 16:33:28
【问题描述】:
我有一个 html 页面(使用 WYSIWYG 完成),在这个页面上我有一个与页面一样大的表单(因为我有很多值我希望能够发送回我的视图,所以我可以添加值在模板中)。
到目前为止一切正常,我可以将我的值发送回我的视图并将它们添加到数据库中。
在这个页面上我也有两个组合框,目标是一旦第一个有一个选定的值,值就会被发送回视图,这样我就可以生成进入第二个组合框的数据。
问题是对于这个操作,我只得到消息
Django csrf 验证失败。请求中止。 csrf 令牌丢失 或不正确
中间件设置:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
模板:
<form id="frm" method="post" enctype="text/plain">{% csrf_token %}
<select name="typeMvmt" size="1" id="typeMvmt" onchange="document.getElementById('ebIdTypeMVT').value = document.getElementById('typeMvmt').value;veriftype();displayProduit();check();send_post();return false;" style="position:absolute;left:220px;top:5px;width:350px;height:28px;z-index:257;">
<option value="0">-- SELECTIONNER UN TYPE DE MOUVEMENT --</option>
{% for typemouvement in typemouvements %}
<option value={{typemouvement.id}}>{{typemouvement.libelle}}</option>
{% endfor %}
</select>
</form>
查看:
def mouvementCreation(request):
idMI = 0
especes = TbEspece.objects.order_by('id')
typemouvements = TbTypeMouvement.objects.all()
#Get Mouvement informations
#Connection to 'erp-site' DB
cursor = connections['erp-site'].cursor()
try:
#Get Produits list from Espe
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()
if request.method == 'POST':
if request.POST.get("form_type") == 'formMVT':
#Handle Elements from first Form
value = request.POST.get('typeMvmt')
Req = TbTypeMouvement.objects.filter(value)
data = getDataQuery(Req)
return HttpResponse(json.dumps(data), content_type = "application/json")
elif request.POST.get("form_type") == 'formEspece':
typemouvement = request.POST.get('idtypemouvement')
soustype = request.POST.get('idsoustype')
recolte = request.POST.get('recolte')
groupe = request.POST.get('groupe')
categorie = request.POST.get('categorie')
code = request.POST.get('code')
collecte = request.POST.get('collecte')
vente = request.POST.get('vente')
stock = request.POST.get('stock')
achat = request.POST.get('achat')
transporteur = request.POST.get('codetransporteur')
blLivreur = request.POST.get('blLivreur', '')
contratClient = request.POST.get('contratClient')
pont1 = request.POST.get('pont1') # BIGINT
numTicket = request.POST.get('numTicket') # INT
dateheure1 = request.POST.get('dateheure1') # DATETIME
poid1 = request.POST.get('poid1') # INT
dsd1 = request.POST.get('dsd1') # INT
pont2 = request.POST.get('pont2') # BIGINT
dateheure2 = request.POST.get('dateheure2') # DATETIME
poid2 = request.POST.get('poid2') # INT
dsd2 = request.POST.get('dsd2') # INT
p1p2 = request.POST.get('p1p2') # INT
livreur = request.POST.get('idlivreur') # BIGINT
vehicule = request.POST.get('vehicule') # VARCHAR
comTicket = request.POST.get('comTicket') # VARCHAR
comLogiciel = request.POST.get('comLogiciel') # VARCHAR
espece = request.POST.get('especeId') # BIGINT
produit = request.POST.get('produitId') # BIGINT
#Connection to 'erp-site' DB
cursor = connections['pontbascule'].cursor()
try:
#Get Produits list from Espece
query = "{CALL SP_webADD_MANUAL_PESEE(%s,%s,%s,%s,%s, %s,%s,%s,%s,%s, %s,%s,%s,%s,%s,%s,%s)}"
arguments = (pont1, numTicket, dateheure1, poid1, dsd1,pont2, numTicket, dateheure2, poid2, dsd2, p1p2,livreur, vehicule,comTicket, comLogiciel,espece, produit)
cursor.execute(query, arguments)
idCreatedPesee = cursor.fetchone()
finally:
cursor.close()
cursor = connections['site'].cursor()
try:
query = "{CALL SP_webCREATE_MVT_INIT(%s,%s,%s, %s)}"
arguments = (idCreatedPesee[0], typemouvement, soustype, transporteur)
cursor.execute(query, arguments)
idCreatedMVT = dictfetchall(cursor)
finally:
cursor.close()
return render(request, 'mouvementCreation.html', locals())
我尝试只用一个表单创建相同的页面,我得到了相同的结果,到目前为止我只将 ajax 与 Datatable 一起使用并且没有问题,希望有人可以分享我的问题。
我使用 Firefox,我查看了设置 cookie 等...但似乎没有任何效果。
【问题讨论】:
-
是否设置了 cookie
csrftoken?如果您使用的是 django,为什么要绕过 ORM 并进行手动提取? -
我不会,因为我没有注意到我需要设置一些 cookie 以使 ajax 工作,我应该如何使用它?而且我不使用 ORM 主要是因为我需要使用存储过程,这样更容易更快。
-
使用 ajax,docs.djangoproject.com/en/1.11/ref/csrf/#ajax 已经有全面的文档和示例。了解存储过程。
-
好的,我会尝试,但我真的不明白为什么实现这个比将 csrf 令牌传递给每个请求的 ajax 更好
-
所以,对我来说不明显的是您是使用 django 表单还是 ajax 发布提交。如果是后者,则需要包含 csrf 令牌作为请求的标头。
标签: ajax django django-csrf