Search code examples
djangomodeladmin

Saving image in static/media folder via django admin issue


Please tell why when I save image via admin I can not see it? Image saves in database but I can not see it if just press link with saved image in admin panel. I get Page not found (404) because there is no image file in this path but if I insert file in folder in my project with the same path,I can see it. Thus, Static files path is defined properly.
I have image field in model:

 photo = models.ImageField(upload_to = 'photo/', blank=True)`

settings:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)
MEDIA_ROOT = os.path.join(BASE_DIR, '..', 'static','media')
MEDIA_URL = '/static/media/'

and seems it should save it in my project static folder but it does not .

my project structure:

project/
       -app/
    -static/
           --media/
                  ---photo/

Solution

  • Media root should be like this -

    MEDIA_ROOT = os.path.join(BASE_DIR, 'static','media')
    

    Ensure the following things - There exists a folder named 'static' in the folder where your project exists. It should contain a folder named 'media'.

    UPDATE: I think your folder structure is wrong. The following should be the structure as per your settings -

    -static                            // MEDIA_ROOT and STATIC_ROOT setting
        -media                         // MEDIA_ROOT setting
    -project(src)
        -app1
            -models.py
            -views.py
            -...
        -static                        // STATICFILES_DIRS setting