【发布时间】:2013-07-16 23:59:50
【问题描述】:
我现在有一些问题,我遇到了 CSRF Cookie not set。请看下面的代码
Python
def deposit(request, account_num):
if request.method == 'POST':
account = get_object_or_404(account_info, acct_number=account_num)
form_ = AccountForm(request.POST or None, instance=account)
form = BalanceForm(request.POST)
info = str(account_info.objects.filter(acct_number=account_num))
inf = info.split()
if form.is_valid():
# cd=form.cleaned_data
now = datetime.datetime.now()
cmodel = form.save()
cmodel.acct_number = account_num
# RepresentsInt(cmodel.acct_number)
cmodel.bal_change = "%0.2f" % float(cmodel.bal_change)
cmodel.total_balance = "%0.2f" % (float(inf[1]) + float(cmodel.bal_change))
account.balance = "%0.2f" % float(cmodel.total_balance)
cmodel.total_balance = "%0.2f" % float(cmodel.total_balance)
# cmodel.bal_change=cmodel.bal_change
cmodel.issued = now.strftime("%m/%d/%y %I:%M:%S %p")
account.recent_change = cmodel.issued
cmodel.save()
account.save()
return HttpResponseRedirect("/history/" + account_num + "/")
else:
return render_to_response('history.html',
{'account_form': form},
context_instance=RequestContext(request))
这里是代码
HTML
<form action="/deposit/{{ account_num }}/" method="post">
<table>
<tr>
{{ account_form.bal_change }}
<input type="submit" value="Deposit"/>
</tr>
{% csrf_token %}
</table>
</form>
我卡住了,我已经清除了cookie,使用了其他浏览器但仍然没有设置csrf cookie。
【问题讨论】:
-
您的
MIDDLEWARE_CLASSES设置中有CsrfViewMiddleware吗? -
在模板中的表单中添加
{%csrf_token%}。 -
@Rohan 它已经存在了,请参阅问题。
-
是的,我已经有了 CsrfViewMiddleware,并且我的表单中已经有了 csrf_token
-
我一直在使用 Django cors 模块并通过 ReactJS 访问它。 (两者都在本地主机上)。我也有这个OP的问题。我发现在 POST 请求中添加
credentials: 'include',然后在 django 的 settings.py 中添加:CORS_ALLOW_CREDENTIALS = True似乎已经解决了问题,而无需在视图中添加@csrf_exempt。它实际上在文档中...pypi.org/project/django-cors-headers-multi *我知道这与上述问题之一有关,但我还不能发表评论,希望能节省其他人我找到 t 所花费的时间