🛷

09. 이미지 넣기

모델에 이미지 필드 추가

cafe에 이미지를 넣어보겠습니다.
tutorialdjango > mysite > main > models.py로 이동하겠습니다. 여기서 null True를 주게 되면 기존에 있는 게시판 게시물은 null 값으로 들어가게 됩니다.
 
  • tutorialdjango/mysite/main/models.py
from django.db import models class Cafe(models.Model): name = models.CharField(max_length = 50) content = models.TextField() mainphoto = models.ImageField(blank=True, null=True) def __str__(self): return self.name
 
위와 같이 수정하셨다면 이제 사진을 처리할 수 있는 라이브러리를 설치 해야 합니다. Pillow라는 라이브러리이며 아래와 같이 설치할 수 있습니다.
(myvenv)root@goorm:/workspace/컨테이너명/mysite# pip3 install pillow
 
모델의 변경사항을 DB에 반영합니다.
(myvenv)root@goorm:/workspace/컨테이너명/mysite# python manage.py makemigrations (myvenv)root@goorm:/workspace/컨테이너명/mysite# python manage.py migrate
 
서버는 다시 구동시켜주세요.
(myvenv)root@goorm:/workspace/컨테이너명/mysite# python manage.py runserver 0:80

Media 설정

이제 사진이 저장될 공간을 설정해주도록 하겠습니다. 이 설정을 하지 않으면 사진을 업로드 할 경우 mysite 바로 아래로 파일이 들어가게 됩니다. 아래 코드의 위치는 settings.py에 맨 마지막입니다.
  • tutorialdjango/mysite/tutorialdjango/settings.py
from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent #...중략... MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/'
💡
django 3.1부터 경로를 표현할 때 os.Path 보다 pathlib.Path를 사용합니다. pathlib.Path를 사용하면 경로를 더 간편하게 표현할 수 있습니다. os.Path 사용시 : MEDIA_ROOT = os.path.join(BASE_DIR, 'media') pathlib.Path 사용시 : MEDIA_ROOT = BASE_DIR / 'media'
 
이미지 파일은 총 3개를 올려보도록 하겠습니다.
cafe_0cafe_0
cafe_0
 
cafe_1cafe_1
cafe_1
cafe_2cafe_2
cafe_2
 
순서대로 cafe_0부터 올리겠습니다.
notion imagenotion image
 
사진을 등록하면 media라는 폴더 안에 이미지 파일이 업로드 된 것을 확인할 수 있습니다.
notion imagenotion image
 
업로드한 파일을 확인하기 위해 해당 cafe를 클릭합니다.
notion imagenotion image
 
아래 Mainphoto에서 cafe_0.jpg를 클릭하니 page를 찾을 수 없다고 뜹니다. 우리가 urls.py에서 URL을 설정해주었었죠? 이러한 이미지도 URL이 필요합니다.
notion imagenotion image
 
notion imagenotion image
 
이번에는 이미지 URL을 설정하러 가보도록 하겠습니다. urls.py에서 아래와 같이 urlpatterns를 넣어주세요. 그러면 이미지가 정상적으로 보입니다.
from django.contrib import admin from django.urls import path from main.views import index, cafelist, cafedetails from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/',admin.site.urls), path('',index), path('cafelist/',cafelist), path('cafelist/<int:pk>/',cafedetails), ] urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
 
notion imagenotion image
 
이제 나머지 두 사진도 넣은 뒤, 이번에는 cafedetails 페이지에서 해당 이미지를 불러와 보도록 하겠습니다. 파일 접근에 대한 자세한 내용은 홈페이지 링크를 참고해주세요.
 
 
tutorialdjango/mysite/main/templates/main/cafedetails.html
<!DOCTYPE html> <html> <head> <title>cafelist</title> </head> <body> <h1>cafedetails</h1> <p>{{cafe.name}}</p> <p>{{cafe.content}}</p> {% if cafe.mainphoto %} <img src="{{ cafe.mainphoto.url }}"> {% endif %} <a href="/cafelist/">목록</a> </body> </html>
 
notion imagenotion image