上传文件时出现Django CSRF问题

时间:2011-03-05 14:51:51

标签: django csrf django-csrf

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

1 个答案:

答案 0 :(得分: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))