본문 바로가기
TTL/9주차 ~ 12주차 TIL (10.24 ~ 11.18)

2022-10-28 TIL (django ImageField)

by dev_junseok 2022. 10. 30.

django 에서 모델을 설계할 때, 이미지 파일을 처리하려면 ImageField를 써야 하는데 몇가지 준비사항이 있다.

 

image = models.ImageField(blank=True, upload_to='%Y/%m/')

일단 모델을 해당 코드와 같이 해준다. blank=True 는 사진을 안 넣어도 되게 설정해 주고 upload_to=~는 media 폴더의 해당 경로에 저장해준다는 의미이다.

 

pip install Pillow

먼저 pillow 라이브러리를 설치해준다. pillow 라이브러리는 이미지를 처리하는 파이썬 라이브러리이다.

#settings.py
STATIC_ROOT = BASE_DIR / "static"
STATIC_URL = "/static/"

MEDIA_ROOT = BASE_DIR / "media"
MEDIA_URL = "/media/"


#urls.py
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

setting.py와 urls.py에 각각 해당 코드들을 추가해 주면 완료이다.

 

참고자료

How to manage static files (e.g. images, JavaScript, CSS) | Django documentation | Django (djangoproject.com)

 

How to manage static files (e.g. images, JavaScript, CSS) | Django documentation | Django

Django The web framework for perfectionists with deadlines. Toggle theme (current theme: auto) Toggle theme (current theme: light) Toggle theme (current theme: dark) Toggle Light / Dark / Auto color theme Overview Download Documentation News Community Code

docs.djangoproject.com