1 Modifying the settings.pyof project, adding
Media_url ' /media/ ' #这个是浏览器访问的地址, for example: Http://127.0.0.1:8000/media/covers/21.png
' Media ') #这个是文件在服务器上保存的根目录, this is the media directory under the Proje root directory, there is covers/21.png, you can access the file by the way above
2 Modify Project's urls.py file to add
... from Import fromimport = ... if settings. DEBUG: + = static (settings. Media_url, Document_root=settings. Media_root) #使得浏览器可以通过MEDIA_URL访问MEDIA_ROOT下的文件
3 Add a field of the file type to the app's models.py , specify the upload location, default to the project root directory
from Import Models class Album (models. Model): = models. Filefield (upload_to="covers") #文件会上传到/media/covers/directory = models. Filefield (upload_to="songs") #文件会上传到/media/songs/directory ...
4 using uploaded files in a template
For example <img src="{{album.album_logo. URL }}"/>
<a href= "{{album.audio_file.url}}" ...
Django-File Upload