新建media文件夹,设置setting.py文件
1 # 上传文件路径设置 2 MEDIA_URL = "/media/" 3 MEDIA_ROOT = os.path.join(BASE_DIR,"media") 4 5 6 # TEMPLATES 加入django.template.context_processors.media在html的地方可以使用 data-url="{{ MEDIA_URL }}{{ org.image }}"/> 7 TEMPLATES = [ 8 { 9 ‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘,10 ‘Dirs‘: [os.path.join(BASE_DIR,‘templates‘)] 11 ,12 ‘APP_Dirs‘: True,13 ‘OPTIONS‘: { 14 ‘context_processors‘: [ 15 ‘django.template.context_processors.debug‘,16 ‘django.template.context_processors.request‘,17 ‘django.contrib.auth.context_processors.auth‘,18 ‘django.contrib.messages.context_processors.messages‘,19 ‘django.template.context_processors.media‘ 20 ],21 },22 },23 ]
设置路由urls.py
- 导入from django.views.static import serve
- 导入settings文件:from . import settings
- 设置路由:url(r‘^media/(?P<path>.*)$‘,serve,{"document_root": settings.MEDIA_ROOT})
1 from django.views.static import serve 2 from . import settings 3 4 url(r‘^media/(?P<path>.*)$‘,{"document_root": settings.MEDIA_ROOT}),
Models的字段配置
1 image = models.ImageField(upload_to="org/%Y%m",verbose_name=‘机构logo‘,max_length=100)