Django MEDIA_URL and MEDIA_ROOT

前端 未结 13 1251
天命终不由人
天命终不由人 2020-11-22 11:36

I\'m trying to upload an image via the Django admin and then view that image either in a page on the frontend or just via a URL.

Note this is all on my local machine

13条回答
  •  借酒劲吻你
    2020-11-22 12:17

    Here What i did in Django 2.0. Set First MEDIA_ROOT an MEDIA_URL in setting.py

    MEDIA_ROOT = os.path.join(BASE_DIR, 'data/') # 'data' is my media folder
    MEDIA_URL = '/media/'
    

    Then Enable the media context_processors in TEMPLATE_CONTEXT_PROCESSORS by adding

    TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                #here add your context Processors
                'django.template.context_processors.media',
            ],
        },
    },
    ]
    

    Your media context processor is enabled, Now every RequestContext will contain a variable MEDIA_URL.

    Now you can access this in your template_name.html

提交回复
热议问题