csrf token Follow up
您好,并提前感谢您。 这是来自以下主题的后续问题(不确定我是否应该在那里发布或开始新线程......:
CSRF令牌丢失或不正确,即使我有{%csrf_token%}
我不确定我需要做什么来使代码使csrfContext工作。 我试图使用ModelForm将数据收集到模型并将其写入MYSQL表。 我收到错误:
1 2 | Reason given for failure: CSRF token missing or incorrect. |
这是代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | from django.shortcuts import render_to_response from djengo.template import RequestContext from django.http import HttpResponse, HttpRequest, HttpResponseRedirect from acmetest.models import Player from acmetest.models import PickForm csrfContext = RequestContext(request) return render_to_response('makepick.html', csrfContext) def playerAdd(request, id=None): form = PickForm(request.POST or None, instance=id and Player.objects.get(id=id)) # Save new/edited pick if request.method == 'POST' and form.is_valid(): form.save() return HttpResponseRedirect('/draft/') return render_to_response('makepick.html', {'form':form}) |
再次,
谢谢您的帮助!
dpbklyn
这样更新您的代码:
1 2 | from django.shortcuts import render # from djengo.template import RequestContext <- this is not valid. |
正如Yuji指出的那样,这两行不是有效的python,而且如果使用
1 2 | # csrfContext = RequestContext(request) # return render_to_response('makepick.html', csrfContext) |
修改您的退货行:
1 2 | # return render_to_response('makepick.html', {'form':form}) return render(request,'makepick.html',{'form':form}) |
我假设我们正在谈论
1 2 3 4 5 6 7 8 9 | def playerAdd(request, id=None): form = PickForm(request.POST or None, instance=id and Player.objects.get(id=id)) # Save new/edited pick if request.method == 'POST' and form.is_valid(): form.save() return HttpResponseRedirect('/draft/') return render_to_response('makepick.html', RequestContext(request, {'form':form})) |
代码中的第一行很难理解,甚至看起来都不是有效的python。 您不能在功能块外部使用