13

I want to upload files to a path that is still in my django project, but in my MEDIA_ROOT path.

When I try to do this I get a SuspiciousOperation error.

Here are the paths as defined in my settings file:

MEDIA_ROOT = os.path.join(os.path.dirname( __file__ ), 'static_serve')
UPLOAD_DIR = os.path.join(os.path.dirname( __file__ ), 'uploads')

I'm doing this because I don't want the files I am uploading to be accessible via the browser and my MEDIA_ROOT path is.

Does anyone have any idea how I get around (fix) this error.

vishes_shell
  • 22,409
  • 6
  • 71
  • 81
imns
  • 4,996
  • 11
  • 57
  • 80
  • You can forbid the web server to publicly serve certain directories under MEDIA_ROOT. – Davor Lucic Sep 02 '10 at 23:20
  • I'm using the testing server right now ... on Windows XP. I'm also not really sure how to do that. – imns Sep 02 '10 at 23:25
  • I don't think development server can, but any production ready web server should be able to limit access to the files. [Here](http://httpd.apache.org/docs/2.0/misc/security_tips.html#protectserverfiles) is the Apache way of doing it for example. – Davor Lucic Sep 02 '10 at 23:29
  • So, is it not possible to upload files outside of the MEDIA_ROOT path? I was hoping it was because I am going to have to redo a ton of code if it's not possible for me to find a solution. – imns Sep 02 '10 at 23:40

1 Answers1

28

Yes there is a way:

From docs:

For example, the following code will store uploaded files under /media/photos regardless of what your MEDIA_ROOT setting is:

from django.db import models
from django.core.files.storage import FileSystemStorage

fs = FileSystemStorage(location='/media/photos')

class Car(models.Model):
    ...
    photo = models.ImageField(storage=fs)
Davor Lucic
  • 28,970
  • 8
  • 66
  • 76
  • 2
    +1 This is worth knowing. Too bad OP will not vote this the best answer. – hughdbrown Sep 22 '10 at 21:28
  • I had the same problem. Did what you (and the docs) said and I get the following exception `FileFields require an "upload_to" attribute.` I pasted the whole block here: http://dpaste.com/hold/533577/ Any ideas? – xpanta Apr 19 '11 at 14:22
  • 1
    Just add the upload_to as the same value as location. – Tom Aug 31 '11 at 19:28
  • 3
    @Tom, you are wrong. location attribute is an absolute path while upload_to is relative path and it is appended to MEDIA_ROOT. – Michał Klich Mar 16 '13 at 16:51