03_Web

[Django] 업로드한 사진을 화면에 표시하는 방법

chuu_travel 2025. 5. 22. 12:18
728x90
Django 업로드한 사진을 화면에 표시하는 방법

 

 

settings.py
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR = BASE_DIR / "templates"
...

# Static files (CSS, JavaScript, Images)

STATIC_URL = "static/"
STATICFILES_DIRS = [BASE_DIR / "static"]

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

# Default primary key field type

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

 

urls.py
...

from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path("admin/", admin.site.urls),
    ...
]

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

 

models.py
from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class BookInfo(models.Model):
    title = models.CharField(max_length=100, null=False) #책제목
    isbn = models.CharField(max_length=20, null=False) #국제표준도서번호(13자리)
    cover_image = models.ImageField(upload_to="book/cover_images", blank=True) #책표지
    ...
    def __str__(self):
        return self.title
 

 

views.py
from django.shortcuts import render
from book.models import BookInfo

# Create your views here.
def best_seller(request):
    all_book = BookInfo.objects.all()
    context = {
        "all_book" : all_book,
    }

    return render(request, "book/best_seller.html", context)

 

 

best_seller.html
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>베스트셀러</title>
</head>
<body>
    ...
    <h1>베스트셀러</h1>
    {% for book in all_book %}
        <img src ="{{ book.cover_image.url }}" alt="표지정보가 없습니다" />
    {% endfor %}
</body>
</html>
728x90