开发者

Django CSRF problem when uploading a file

开发者 https://www.devze.com 2023-02-14 20:07 出处:网络
I\'m getting the \"CSRF token missing or incorrect\" error whenever I try the following code: def format(request):

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

精彩评论

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