Day 14 Django for KN

김의석 ·2024년 2월 20일

Django

목록 보기
14/39

Django for KN(Koinonia)

  • 해당 문서는 Django 강의가 리뉴얼 되어 이전 과정들을 복습하는 문서로 작성 됨.

Django를 위한 가상환경과 프로젝트 및 앱생성

프로젝트와 앱 URLS 라우팅

앱등록

templates directory를 이용한 html 전송

  • views.py return rendering
def index(request: HttpRequest) -> HttpResponse:
    return render(request=request, template_name="hottrack/index.html", context={})
    # render 함수 : 템플릿을 사용하여 HTML 페이지를 생성
    # 두 번째 매개변수로 컨텍스트 데이터를 받는다, context={Dict}
  • templates 찾기
# project settings.py

EMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        # True 옵션은 django가 각 앱의 templates 디렉토리를 찾아 템플릿을 로드하려고 시도합니다.
        "APP_DIRS": True,

템플릿에서 데이터 렌더링 하기

Rendering 이란?
Django 웹 프레임워크 서버에서 데이터와 템플릿을 결합하여 HTML을 생성하고, 이를 클라이언트에게 전달하여 브라우저에서 화면에 나타내는 과정

  • Rendering시 데이터는 전처리를 , html은 적절한 context 배치가 중요하다

model.py

@dataclass
class Song:
   id: str
   rank: int
   album_name: str
   name: str
   artist_name: str
   cover_url: str
   lyrics: str
   genre: str
   release_date: date
   like_count: int

 @classmethod
   def from_dict(cls, data: Dict) -> Song:
       return cls(
           id=data.get("곡일련번호"),
           rank=int(data.get("순위")),
           album_name=data.get("앨범"),
           name=data.get("곡명"),
           artist_name=data.get("가수"),
           cover_url=data.get("커버이미지_주소"),
           lyrics=data.get("가사"),
           genre=data.get("장르"),
           release_date=date.fromisoformat(data.get("발매일")),
           like_count=int(data.get("좋아요")),
       )
  • Song : json 파일이 역직렬화를 통해 python 객체가 된 후 song class를 통해 출력된 instance가 list로 담김.
    이후 Song 객체의 속성들 (id, rank, album_name, name, artist_name, cover_url, lyrics, genre, relme, like_count 등) 데이터에 접근 할 수 있다.

views.py

import json
from urllib.request import urlopen
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render
from hottrack.models import Song

def index(request: HttpRequest) -> HttpResponse:
   melon_chart_url = "https://raw.githubusercontent.com/pyhub-kr/dump-data/main/melon/melon-20230910.json"
   json_string = urlopen(melon_chart_url).read().decode("utf-8")

# JSON 파일을 python 객체로 역직렬화
   song_list = [Song.from_dict(song_dict) for song_dict in json.loads(json_string)]

   return render(
       request=request,
       template_name="hottrack/index.html",
       context={
           "song_list": song_list,
       },
   )
   
   print(song_list)
   [Song(id='36713849', rank=1, album_name='Love Lee', name='Love Lee', artist_name='AKMU (악뮤)', cover_url='https://cdnimg.melon.co.kr/cm2/album/images/113/09/190/113090_20230818161008_500.jpg', lyrics="You know\n내 스타일이 아닌 음악을 들어도\nYou know\n좋아하지 않는 음식을 먹어도\n우산 없이 비가 와 홀딱 다 젖어도 좋아\nI love it be음같이 비기비기닝\n춤추고 싶어 빌리빌리진\n우리 앞 우리 옆 시기시기질투\n자유로운 날갯짓 훨훨훨\n꽃송이가 나를 삼킬 걸\n알면서 난 뛰어들었어 \nJump j-j-jump jump jump \nDu durudu durudu du durudu\n\nSpell L.o.v.e.L.e.e\n이름만 불러도 you can feel me\n눈빛만 봐도 알면서 my love\n\nYou know\n아끼는 옷에 coffee를 쏟아도\nYou know\n내가 사준 걸 다시 또 잃어도 좋아\nI don't care I just care about you\n\n여기 어때 how you like that\n다 퍼주고 될게 빈털터리\nJubilate 박수갈채\n안 반하고 누가 배겨 love s\n체크무늬 벌집 두 눈에\nHoney help honey help\n\nSo lovely day so lovely\nErrday with you so lovely\nDu durudu durudu du durudu\n\nSpell L.o.v.e.L.e.e\n이름만 불러도 \n눈빛만 봐도 알면서 my love\n\n누구 사랑 먹고 그리 이쁘게 컸니\nMommy or your daddy or them both\nLovey-dovey things 너의 곁에 everyday\nGood morning good night\n너의o lovely\nErrday with you so lovely\nDu durudu durudu du durudu\n\nSpell L.o.v.e.L.e.e\n이름만 불러도 you can feel me\n눈빛만 봐도 알면서 my love\n", genre='댄스', relme.date(2023, 8, 21), like_count=55091)]

index.html 과 _song.html

  • 순회로 코드를 간단히 만들기
<!-- 수정 전 순회-->
       <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">
                <div class="col">
                    {% include "hottrack/_song.html" %}
                </div>
                <div class="col">
                    {% include "hottrack/_song.html" %}
                </div>
                <div class="col">
                    {% include "hottrack/_song.html" %}
                </div>
                <div class="col">
                    {% include "hottrack/_song.html" %}
                </div>
            </div
            
<!-- 수전  순회 -->
   <div class="album py-5 bg-body-tertiary">
        <div class="container">
            <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">
               {% for song in song_list %}
                <div class="col">
                    {% include "hottrack/_song.html" with song=song only %} 
                  <!-- include template 내에서 외부 template를 가져올 때 사용 -->
                  <!-- with song=song only 추가시 지정된 context만 html과 render 됨 -->
                </div>
               {% endfor %}
            </div>
        </div>
    </div>
  • class="col"은 HTML 요소에 부여된 CSS 클래스(class)를 나타냅니다. CSS 클래스는 해당 HTML 요소에 스타일이나 레이아웃을 적용하기 위해 사용됩니다.

  • 탬플릿 문법 {% %}


{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}!</p>
{% else %}
    <p>Please log in.</p>
{% endif %}
  • 조건식이 있는 경우에 사용
profile
널리 이롭게

0개의 댓글