【发布时间】:2011-07-09 10:31:41
【问题描述】:
每当我尝试以下代码时,都会收到“CSRF 令牌丢失或不正确”错误:
def format(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/formatter/login/?next=%s' % request.path)
else:
if request.method == 'POST':
csv_file = request.FILES['file']
filedata = format_csv_file(csv_file)
[...]
response = HttpResponse(filedata)
response['Content-Type'] = 'application/dat'
response['Content-Disposition'] = 'attachment; filename="' + str(datestamp) + ".dat\n\n"
return response
我的表单中也有 {% csrf_token %}。我只是不知道我在这里错过了什么。任何帮助将不胜感激。谢谢!
编辑:根据要求,这是呈现模板的视图:
def main_view(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/formatter/login/?next=%s' % request.path)
else:
return render_to_response('main.html')
这是模板(相关部分):
<form enctype="multipart/form-data" action="format/" method="POST">{% csrf_token %}
<p>Please select a file to convert: <input type="file" name="file" onchange="this.form.submit()"></p>
<p class="smalltext"><i>**Upon selecting a file to convert, you will be prompted to download the finished result</i>
</form>
【问题讨论】:
-
向我们展示呈现表单的代码。
-
你能给我们展示一下 HTMl 或渲染后的表单吗?可能是中间件或 context_processors 没有正确安装
-
你秒杀我。没有什么比我们自己找到答案更重要了。
-
musashi-您应该在下面回答您的问题,因为我只是不小心回答了它:)
标签: django csrf django-csrf