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
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
'TTL > 9주차 ~ 12주차 TIL (10.24 ~ 11.18)' 카테고리의 다른 글
| 2022-11-01 TIL (백엔드와 프레임워크 공부) (0) | 2022.11.02 |
|---|---|
| 2022-10-31 TIL (SerializerMethodField) (0) | 2022.10.31 |
| 2022-10-27 TIL (0) | 2022.10.28 |
| 2022-10-26 TIL (로그인 인증의 종류, JWT 알아보기) (0) | 2022.10.27 |
| 2022-10-25 TIL (장고 시리얼라이저란 serializer) (0) | 2022.10.25 |