您好,并提前感谢您。这是来自以下主题的后续问题(不确定我是否应该在那里发布或开始新线程......:
CSRF token missing or incorrect even though I have {% csrf_token %}
我不确定我需要做些什么来使csrfContext工作的代码。我试图使用ModelForm将数据收集到模型并将其写入MYSQL表。我收到了错误:
Reason given for failure: CSRF token missing or incorrect.
以下是代码:
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
答案 0 :(得分:0)
我假设我们正在讨论playerAdd
视图 - 您需要将RequestContext
传递给那里的回复。
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。您不能在功能块外使用return
。
答案 1 :(得分:0)
如此更新您的代码:
from django.shortcuts import render
# from djengo.template import RequestContext <- this is not valid.
正如Yuji指出的那样,这两行不是有效的python,而且如果你使用render
快捷方式则不需要它们。
# csrfContext = RequestContext(request)
# return render_to_response('makepick.html', csrfContext)
修改退货行:
# return render_to_response('makepick.html', {'form':form})
return render(request,'makepick.html',{'form':form})