djangoimagefieldmedia-url

django: ImageField, MEDIA_ROOT, MEDIA_URL, how to set correctly


How should MEDIA_ROOT and MEDIA_URL be set correctly in context of ImageField? How should I set upload_to parameter for an ImageField? Comments for MEDIA_ROOT and MEDIA_URL are scarce, so I would like to know, what are they used for and how to set them correctly.


Solution

  • The MEDIA_ROOT is the directory where you want the files to go, the MEDIA_URL needs to be a URL that leads to that same directory path.

    The upload_to option can either be a directory within that directory, so upload_to="foo" would go into the "foo" subdirectory of MEDIA_ROOT.

    Or it can be a function that takes the image-field instance and the proposed base filename, and returns the real filename you want to use. So

    upload_to=get_photo_path 
    

    and:

    def get_photo_path(instance, filename):
      if not filename: return ""
      exts = re.search('[.]([^.]*)$',filename)
      if exts is None:
        ext  = ''
      else: 
        ext = '.'+exts.group(1)
      return "newname%s" % (ext)
    

    Would rename the file but keep the extension. Note that "newname." would still be in the MEDIA_ROOT directory - you don't need to return "/usr/whatever/something/foo/newname.". It already tacks MEDIA_ROOT on there for you.

    Update:

    FYI, it's nice to know about

    <modelobject>.<imagefieldname>.field.generate_filename( <modelobject>, proposed_name )
    

    This is how you can generate the partial path that the image will go into, from outside the model. You need to manually prepend MEDIA_ROOT to this to make it an absolute path.