Forums

file upload problem

Apologies in advance. I'm a beginner so probably making some basic mistake. I have a Django app which works fine locally on my computer. It also (after a bit of fiddling) works fine on Pythonanywhere, except for file uploads through the app.

The file upload is through a form based on a model with a filefield:

 bll = models.FileField(upload_to= "uploads", verbose_name = "Photo")

which is then saved:

   form = UpdatePersonForm(request.POST, request.FILES, instance = person)

    if form.is_valid():

        form.save()

Settings:

MEDIA_URL = '/media/'
MEDIA_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['media']))

I can upload files through the "files" section of Pythonanywhere. And I have mapped url to directory in the "web" section, which presumably worked because I can access the files directly via [myusername].pythonanywhere.com/media/uploads/[filename]. And the other aspects of the form work fine, including changing bll.url. If I try to upload through the app a file which I've already uploaded through the files section, it can then be viewed through the app.

So the one thing that isn't working is that the files which I'm trying to upload via the app aren't reaching pythonanywhere. I've looked at the error log but it doesn't seem to help. Might be something to do with WSGI (don't really understand that side of things) but not sure why that would affect only file uploads.

Grateful for any help. Thanks.

Do you get an error of any kind when you try to upload the files?

Not as far as I can tell - no obvious sign of any error, the files just don't show up the other end.

Update - I have just located the uploaded files! I'll explain more in a second.

For some reason they seem to have ended up in:

home/MichaelCoburn/home/MichaelCoburn/media/uploads

rather than just

home/MichaelCoburn/media/uploads.

Any idea why that has happened?

Ah, I think I see what might have happened. Your code:

MEDIA_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['media']))

Is probably running with BASE_DIR set to /home/MichaelCoburn/. This then gets split by "/", giving ["home", "MichaelCoburn"], to which you add ["media"], giving ["home", "MichaelCoburn", "media"]. You then join that together, which gives home/MichaelCoburn/media. That's a relative path -- that is, it's relative to the directory in which your website's code is running, which happens to be /home/MichaelCoburn/, so the full absolute path to the media directory is /home/MichaelCoburn/home/MichaelCoburn/media/uploads.

Try specifying it this way instead:

MEDIA_ROOT = os.path.join(BASE_DIR, "media")

Thanks very much indeed for investigating, much appreciated. I'll try that.