5

I have a problem with file uploading in my django project. So the question is: how can I pass files to django view through jquery ajax?

At this moment I have

script:

<script type='text/javascript'>
$(document).ready(function() {
    var csrf_token = $('input[name="csrfmiddlewaretoken"]').val();
    $('#upload').click(function() {
        $.ajax({
            csrfmiddlewaretoken: csrf_token,
            type: 'POST',
            url : '../ajax/upload_file/',
            enctype: "multipart/form-data",
            data  : {
                'file': $('#file').val()
            },
            success: function(data) {
                console.log(data)
            }
        })
    })
})
</script>

template:

 <form method="" action="" name='upload_form' id='upload_form' >{% csrf_token %}
    <input type='file' name='file' id='file' />
    <input type='button' value='Upload' id='upload'/>
 </form>

and view:

@csrf_exempt
@xhr_to_json
def verifyFile(request):
    if request.is_ajax():
        file = request.FILES['file']
        return {'message': file}
    else: 
        return HttpResponseForbidden()

now im getting

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 111,      in get_response
response = callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py", line 77, in wrapped_view
    return view_func(*args, **kwargs)
 File "/home/vova/git/LV-  083_LAMP.git/Testcase_Project/Testcase_Project/views/decorator.py", line 6, in wrapper
   data = func(*args, **kwargs)
  File "/home/vova/git/LV-   083_LAMP.git/Testcase_Project/Testcase_Project/views/testcase.py", line 96, in verifyFile
    request.FILES['file']
  File "/usr/local/lib/python2.7/dist-packages/django/utils/datastructures.py", line     258, in __getitem__
    raise MultiValueDictKeyError("Key %r not found in %r" % (key, self))
MultiValueDictKeyError: "Key 'file' not found in <MultiValueDict: {}>"

is it possible to do it without external libraries?

4
  • 1
    Have you tried file = request.FILES.get('file') Commented Apr 4, 2013 at 12:33
  • returning Object {message: null} Commented Apr 4, 2013 at 12:52
  • url is right. i can return any other data and it will work Commented Apr 4, 2013 at 13:04
  • same error Key 'file' not found in <MultiValueDict: {} Commented Apr 4, 2013 at 13:07

3 Answers 3

7

Try this:

def upload(request):
  id = request.POST['id']
  path = '/var/www/pictures/%s' % id
  f = request.FILES['picture']
  destination = open(path, 'wb+')
  for chunk in f.chunks():
    destination.write(chunk)
  destination.close()
  # return status to client
  ...

You can read the full tutorial here: http://www.laurentluce.com/posts/upload-to-django-with-progress-bar-using-ajax-and-jquery/

Sign up to request clarification or add additional context in comments.

2 Comments

the problem is that request.FILES is empty
@vovaminiof if request.FILES is empty, perhaps take a look at this answer: stackoverflow.com/a/5567063/11483646
1
@csrf_exempt
@xhr_to_json
def verifyFile(request):
    if request.is_ajax():
        file = request.FILES['file']
        return HttpResponse(file)
    else: 
        return HttpResponseForbidden()

<form method="POST" action="" name='upload_form' id='upload_form' enctype="multipart/form-data">
    {% csrf_token %}
    <input type='file' name='file' id='file' />
    <input type='button' value='Upload' id='upload'/>
</form>

2 Comments

remove this if request.is_ajax(): in your view and the else statement. test if return to None again
complete also your form in your template so that it will read the file pass
0

//html

<form  id = "form_id"   method = "POST" action = "#" enctype="multipart/form-data"> {% csrf_token %}
                        {{modelform_filefield}}
                        <input type = "submit" value="Post"/>
                    </form>

//javascript code

<script>
    $(function(){
    $("#form_id").submit(function(){
    var data = new FormData($('#form_id').get(0));
                $.ajax({
                    type:"POST",
                    url: "your_upload_url",
                    data : data,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function(data){
    alert('success');
                    },
                    failure: function(){
                        $(this).addClass("error");
                    }
                });
                return false;
    });
    });
</script>

This will extract the file and forms data from the client end. The URL links to the views where your files are processed and stored.

//views.py

def upload(request):
    if request.is_ajax():
        form = <modelFormName>(request.POST, files=request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponse("form saved")
        else:
            return HttpResponse("form invalid")

    return HttpResponse("not a ajax request")

This should do the trick

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.