1

每当我尝试以下代码时,都会收到“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>
4

1 回答 1

1

我已经回答了我自己的问题;RequestContext 未在呈现表单模板的视图中使用。这是更正后的版本:

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', context_instance=RequestContext(request))
于 2011-03-05T15:26:25.193 回答