Satheesh Panduga
Satheesh Panduga

Reputation: 818

Cannot upload file to media path in Django when using Ajax

I'm trying to upload the image file to the Media url specified in my setting.py and store the path of an image in the database table. However, I could not achieve this when using Ajax for uploading the image file..

template.html

<div class="profpic" style="background:url(../../../static/app/img/test.png);background-size:cover">
            <input type="file" id="picpath" name="picpath" class="uploadpic" value=""/>
        </div>

Ajax :

function saveprof() {
            $.ajax({
                type: "POST",
                url: "saveprof",
                enctype: 'multipart/form-data',
                async: true,
                data: {
                    'picpath_Aj': $('#picpath').val(),
                    'profemail_Aj': $('#profemail').val(),
                    'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
                },
                success: function (data, textStatus, jqXHR) {
                    $('#message').html(data);
                }
            });
        }

Views.py

def saveprof(request):
if request.method == "POST":
    picpathV = request.POST['picpath_Aj']
else:
    profemailV = ''
    response_data = 'Nothing to update!'
    return HttpResponse(response_data, content_type="text/plain")
response_data = 'Empty'
try:
    res=td_table.objects.filter(id=request.session.get('proid')).update(picpath=picpathV)
except:
    response_data = 'Something went wrong!'
return HttpResponse(response_data, content_type="text/plain")

Above code is working fine, but I could save only the file path like ('C:\fakepath\file.jpg').. and file is not getting saved to the media path provided in the Settings.py.

I could upload the file when I use request.FILES in the view, when used Django form.. but in my case, I need to get this done using Ajax function only. What could be the wrong in the view code ?

Here is my models.py

class td_Student(models.Model):
firstname = models.CharField(max_length=300,blank=True)
picpath=models.FileField(upload_to=unique_filename)

def unique_filename(instance, filename):
    ext = filename.split('.')[-1]
    filename = "%s_%s.%s" %(uuid.uuid4(),time.strftime("%Y%m%d_%H%M%S"), ext)
    return os.path.join('documents/documents/'+time.strftime("%Y%m%d"), filename)

As per above logic, file name should be like 'documents/documents/20150716/a1f81a80-ce6f-446b-9b49-716b5c67a46e_20150716_222614.jpg' - This value should be stored in my database table.

settings.py

MEDIA_ROOT = 'C:/DJ/'
MEDIA_URL = '/DJ/'

Upvotes: 0

Views: 1612

Answers (1)

kumar
kumar

Reputation: 2620

The problem is not with Django, but with your AJAX post, you are just passing the name, hence Django receives and saves the name.

Solution: Once the user selects a file, change event will be emitteed, on this change evet you will have to grab the file instance using event.target.files store it in a local variable and pass it to picpath_Aj'.

// Add events
$('input[type=file]').on('change', prepareUpload);

// Grab the files and set them to our variable
function prepareUpload(event)
{
  files = event.target.files;
}

Detailed guide is here http://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax

And alternative Django solution with JS and backend code is https://github.com/skoczen/django-ajax-uploader

Upvotes: 2

Related Questions