AI 웹 개발 과정/팀 프로젝트

팀 프로젝트 04 : 추천 시스템 페이지 - 3일차 / django 프로젝트 파일 구성 [templates, static]

만 기 2022. 6. 7. 23:09

 

1. 프로젝트 구성

 

- 프로젝트 폴더에 기능별 app 폴더들이 있고, templates와 static 폴더도 별도로 두어 app 폴더에서 필요한 html 과 css, js, image 를 가져다 쓴다. 

 

 

2. static 파일 (css, js, image) 관리하기

 

- settings.py 하단에 static URL 이 명시되어있다.

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'

 

 

- static 폴더를 프로젝트 폴더 바로 밑에 생성하고, static 폴더 하위에 css, js, image 폴더를 각각 만들어 관리한다.

 

- 폴더를 생성했으면, settings.py의 static URL 밑에 폴더를 만들었다고 알려준다.

import os
# settings.py 상단에 임포트 해준다.
...
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]


# app 폴더안에 static 폴더를 생성한 경우 !!!
STATICFILES_DIRS = [
	BASE_DIR / 'static',
    os.path.join(BASE_DIR, 'app폴더명', 'static')
]

 

- html 파일에서 static 사용하기

{% load static %}
# static 폴더 로드

# html 상단
<!DOCTYPE html>
<html lang="en">
<head>
...
	# 사용할 css 파일과 js 파일 링크 
	<link rel="stylesheet" href="{% static 'css/rating.css' %}">
    <script defer src="{% static 'js/rating.js' %}"></script>
...
# 이미지 파일 가져오기
<img src="{% static 'images/logo.png' %}"/>

 

*** 참조 링크

How to manage static files (e.g. images, JavaScript, CSS) | Django documentation | Django (djangoproject.com)

 

How to manage static files (e.g. images, JavaScript, CSS) | Django documentation | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com

 

https://0ver-grow.tistory.com/912

 

[장고 입문] 9. Static 실전 / StaticFiles경로 설정 / Static_Root 사용 이유?

1. STATICFILES 경로 입력 프로젝트폴더의 settings.py 파일에서 최하단으로 내려보자 STATIC_URL : static파일이 제공되는 URL 위 코드에 이어서 STATICFILES_DIRS을 만들어 줘야 한다. 이를 위해 Static file..

0ver-grow.tistory.com

 

 

 

 

3. base.html 로 html 폼 구성하기

 

- 사용하는 이유 :  중복으로 사용되는 기본 폼 html 을 만들어두고 다른 html 에서 편하게 가져다 쓰기 위함

 

- settings.py 의 TEMPLATES

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates']
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

# 또는 'DIRS': [os.path.join(BASE_DIR, 'templates')],

 

- base.html

{% load static %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    <!-- 참조할 css, js -->
    {% block link %}
    {% endblock link %}

    <!-- 페이지별 타이틀 -->
    {% block title %}
    {% endblock title %}
</head>
<body>

    {% block content %}
    {% endblock content %}

</body>
</html>

 

- 다른 html 에서 base.html 적용

{% extends 'base.html' %}
{% load static %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    <!-- 참조할 css, js -->
    {% block link %}
        <link rel="stylesheet" href="{% static 'css/rating.css' %}">
        <script defer src="{% static 'js/rating.js' %}"></script>
    {% endblock link %}

    <!-- 페이지별 타이틀 -->
    {% block title %}
        <title>test</title>
    {% endblock title %}

</head>
<body>
{% block content %}
   <h1>test</h1>
{% endblock content %}

</body>
</html>
  • {% extends 'base.html' %} 로 불러 쓰겠다고 선언
  • {% block %} {% endblock %} 사이에 해당 html 에 필요한 코드들을 작성하면 된다.

 

*** 참조 링크 ***

django 기초 - templates 관리하기 (base.html) (tistory.com)

 

django 기초 - templates 관리하기 (base.html)

base.html {% load static %} <!DOCTYPE html> Document {% block style %} {% endblock %} {% block content %} {% endblock %} 기본적인 틀은 위와 같다. 여기에 필요에 따라 코드를 수정 및 추가하게 된다. 추..

inuplace.tistory.com

 

 

 

4.  맥주 데이터 csv 파일 모델링하여 db에 저장

 

- beer/models.py 

from django.db import models


class Beer(models.Model):
    class Meta:
        db_table = "Beer"

    name = models.CharField(max_length=256, default='')
    style = models.CharField(max_length=256, default='')
    category = models.CharField(max_length=256, default='')
    aroma = models.TextField(default='')
    flavor = models.TextField(default='')
    balance = models.TextField(default='')
    season = models.TextField(default='')
    paring_food = models.TextField(default='')
    body = models.TextField(default='')
    rating = models.FloatField(default=0.0)
    img_url = models.ImageField()

 

- beer/views.py : migrate 하고 장고 첫 실행 후 삭제하지않으면 중복 저장 된다.

import csv# Create your views here.
path = "templates/맥주_cbf_data.csv"
file = open(path, encoding='UTF-8')
reader = csv.reader(file)
for i, row in enumerate(reader):
    if i > 0:
        Beer.objects.create(
            name = row[3],
            style = row[4],
            category = row[5],
            aroma = row[6],
            flavor = row[7],
            balance = row[8],
            season = row[9],
            paring_food = row[10],
            body = row[11],
            rating = row[12],
            img_url=f'images/beer/{row[3]}.png'
        )