开发者

Django CSRF problem when uploading a file

I'm getting the "CSRF token missing or incorrect" error whenever I try the following code:

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

I've got the {% csrf_token %} in my form also. I just don't know what I'm missing here. Any help would be appreciated greatly. Thanks!

EDIT: As requested, here's the view that renders the template:

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')

And here's the template (relevant part):

<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>


I've answered my own question; RequestContext wasn't being used in the view that renders the form template. Here's the corrected version:

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))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜