django中media媒体路径设置
1、创建一个app02, 并在settings.py里面设置
2.在创建一个media文件,并在settings. py里面设置
MEDIA_ROOT = os.path.join( BASE_DIR , "media" )
3、在settings.py里面设置媒体文件保存的路径
from django.contrib import admin from django.urls import path,re_path from app01 import views from django.views.static import serve from LoginTest import settings urlpatterns = [ path('admin/', admin.site.urls), path("login/", views.login), path("index/", views.index), path("home/", views.home), path("logout/", views.logout), path("set_session/", views.setSession), #手动添加对外开放的后端服务器资源 re_path(r"^media/(?P<path>.*)/", serve, {"document_root": settings.MEDIA_ROOT}), ]
4、在app02/models.py里面, 创建一个模型,用于上传文件
from django.db import models # Create your models here. class UserDetail(models.Model): headPhoto = models.FileField(upload_to="head") hobby = models.TextField(max_length=200)
5、执行makemiagrtions和migrate, 同步数据库
6、在app02/admin.py里面注册模型 UserDetail
from django.contrib import admin from app02.models import UserDetail # Register your models here. admin.site.register( UserDetail)
7、创建超级用户admin, 并使用admin添加UserDetail
添加完成后,数据库UserDetail表就多了一条数据
对应的工程目录 media/head下,也生成了一个head1.jpg文件
8、手动在浏览器里面访问http://127.0.0.1:8080/media/head/head1.jpg/