Django-simple file upload configuration

Django-file upload

  • FileField / ImageField

pS: If you use ImageField, you need to install the Pillow library

File upload setting upload path

  • In the settings.py configuration file, set the root directory of the file upload
# 设置 文件上传的 根目录

MEDIA_ROOT = BASE_DIR / 'media'

# 设置 文件上传的 访问 地址前缀

MEDIA_URL = "/media/"

Set the access route to upload files in urls.py

from django.conf.urls.static import static
from django.conf import settings


urlpatterns = [
	
	...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


In the model, use file upload attributes

  • FileField
  • ImageField

Through the upload_to attribute, set the file storage location, upload_to is set to a directory, which is relative to MEDIA_ROOT

Requirements for the form of file upload in the template

  • The form must be submitted by POST
  • The form must set enctype='multipart/form-data'

Get the uploaded file in the view function

request.FILES 

For other usage, please refer to request.GET/ request.POST

Guess you like

Origin blog.csdn.net/qq_40679091/article/details/109148054