我正试图从2个不同的下拉列表中获取POST,我从POST获得了参数,但是我遇到了CSRF令牌的问题....
index.html
gip_draw_rectangle(boxes[i].x, boxes[i].y, boxes[i].x + box_size, boxes[i].y + box_size, blue);
尽管我在html表单中使用了csrf令牌,但它没有用...
views.py
<form method="post" action="/getdata/">{% csrf_token %}
<select name="Lista">
<option selected="selected" disabled>Objects on page:</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
<select name="Lista2">
<option selected="selected" disabled>Objects on page:</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
<input type="submit" value="Select">
</form>
models.py
from django.http import HttpResponse
from django.template import loader
from django.shortcuts import render
from view.forms import *
from django.shortcuts import render_to_response, redirect
from view.models import *
def index(request):
if request.method == 'POST':
Lista = request.POST.get('Lista')
print "Lista 1 "+Lista
Lista2 = request.POST.get('Lista2')
print "Lista 2 "+Lista2
#FORMS
form = FormsLista(request.POST)
if form.is_valid():
newPost = Lista(num_lista_1=Lista, num_lista_2=Lista2)
newPost.save()
context = {
'Lista': Lista,
'Lista2': Lista2
}
return render(request, 'showdata.html', context)
else:
template = loader.get_template('index.html')
return HttpResponse(template.render())
我通过这种方式激活了cookie ...
答案 0 :(得分:1)
要使用Django's CSRF protection,您需要使用请求对象呈现模板:
template = loader.get_template('index.html')
return HttpResponse(template.render(request=request))
如果您在任何地方使用render
,您的代码会更加一致:
return render(request, 'index.html')
要修复[view] didn't return an HttpResponse
错误,您需要确保索引视图始终返回HttpResponse
。当表单无效时,您返回None
POST请求。在Django中执行以下操作非常常见:
def index(request):
if request.method == 'POST':
...
form = FormsLista()
return render(request, 'index.html', {'form': form})
然后,在模板中,您可以显示表单错误。有关详细信息,请参阅rendering forms上的文档。