UPLOAD file to django
<p>I try to upload a file to django from html through an ajax call.</p>

<p>CLIENT SIDE:</p>

<pre><code>&lt;input type="file" class="text-field" name="media"&gt;
&lt;input type="button" class="btn" value="SEND"&gt;


var files;

            $('.text-field').change(function(){
                files = this.files;
                console.log(files);
            });

$('.btn').click(function(){
                var data = new FormData();

                $.each(files, function(key, value){
                    data.append(key, value);
                    console.log(key + ' : ' + value);
                    console.log(value);
                });



$.ajax({
                type: 'POST',
                url: 'url',
                enctype: 'multipart/form-data',
                data: data,
                cache: false,
                dataType: 'json',
                processData: false,
                contentType: false,
                success: function(data){
                    console.log(data);
                }
            }); 
</code></pre>

<p>BACK side:</p>

<pre><code>@csrf_exempt def my_file(request):
    print request.POST
    print request.FILES
</code></pre>

<p>result:</p>

<pre><code>MultiValueDict: {u'0': [TemporaryUploadedFile: about.php (application/octet-stream)]}
</code></pre>

<p>Please help me to understand how I can upload a file</p>

<p>To upload a file through Django, you will most likely have to use django forms. Here is an example as for how to upload a file:</p>

<pre><code>def upload_file(request):
if request.method == 'POST':
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
        instance = ModelWithFileField(file_field=request.FILES['file'])
        instance.save()
        return HttpResponseRedirect('/success/url/')
else:
    form = UploadFileForm()
return render(request, 'upload.html', {'form': form})
</code></pre>

<p>As you can see the form validates your input, and then you can save the file in to your server. For more information about this topic please use the django documentation:</p>

<p><a href="https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/</a></p>

python django file