Why am I getting NoneType when uploading a file from js to django?

  • 0
    I make a chat on channels. I want to make it possible to download files. As I found out, you first need to get the file in js, then pass it to the python function to load this file into the folder, then return the path to this photo to the sockets. I do this:
    <input id="upload" type="file" onchange="selectFile()">
    function selectFile() {
    	e = document.getElementById('upload')
      if(e.files[0]) {
        let item = e.files[0];
        let filesize = item.size;
        let filesizeMB = (filesize / (1024 * 1024)).toFixed(2);
        if (filesizeMB >= 3) {
          alert('Максимальный размер фотографии 3 мб');
        } else {
    var $input = $("#uploadimage");
        var fd = new FormData;
        fd.append('csrfmiddlewaretoken', '{{ csrf_token }}');
        fd.append('image_message', item);
            url: '/chat/upload/',
            type: 'POST',
            data: fd,
            processData: false,
            contentType: false,
    <!--        csrfmiddlewaretoken: '{{ csrf_token }}',-->
            success: function (data) {
      } else {
        alert('Файл не найден');

    I get these files in django view:
    def upload_private_chat(request):
        a = request.POST.get('image_message')
        a2 = request.POST.get('csrfmiddlewaretoken')
        print(a, a2)
        if request.method == 'POST':
            with open('jghghj.png', 'w') as file:
                os.chdir(r'/media') # X1
            # a = request.POST.get('image_message')
            # print(a)
        return HttpResponse("ok")

    If a2, that is, textual information I receive and write it without problems (although I do not need it), then on the output of photos (and when loading) output 'TypeError: write () argument must be str, not None'
    JavaScript Anonymous, May 9, 2019

  • 1 Answers
  • 0
    We needed another handler (which simply saves the file, and gives the path to it in js).

    def upload_private_chat(request):

    fs = FileSystemStorage(location='./media/message_image')

    myfile = request.FILES.get('image_message')
    filename = fs.save(myfile.name, myfile)
    uploaded_file_url = fs.url(filename)

    return HttpResponse( uploaded_file_url)

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!