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
'03_Web' 카테고리의 다른 글
| [Django]Paginator를 활용한 페이징(paging) (3) | 2025.05.22 |
|---|---|
| [Django]장고 템플릿 태그 주석 다는법 (0) | 2025.05.22 |
| [Django] forms에 체크박스 넣는방법 (7) | 2025.05.20 |
| [HTML, Javascript]SELECT BOX(셀렉트 박스)를 선택하면 다른 SELECT BOX가 유동적으로 변하게 만드는법 (0) | 2025.04.01 |
| include태그로 html을 html에 끼워넣기 (0) | 2025.04.01 |