Search code examples
djangocsrfdjango-csrf

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>

Solution

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