[Django] #3.Django의 기본 구조

Lynn·2020년 12월 3일
0

Django

목록 보기
4/7
post-thumbnail

views.py / urls.py

views.py : 화면에 어떤 데이터를 보여줄 것인지를 정의

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello world.")

urls.py : 어떤 path(도메인 이하 url)에 어떤 화면을 띄울지를 맵핑 (routing)

하나의 프로젝트 내에 여러 앱이 존재할 수 있기 때문에
각 웹앱의 urls.py를 base path에 맵핑되도록 한다.

⬇️ first/urls.py (웹앱)

from django.urls import path
from first import views # views.py 파일을 임포트 한다.

urlpatterns = [
    path('', views.index, name='index'), # views 파일의 index 메소드에 연결
]

⬇️ firstdjango/urls.py (웹프로젝트)

from django.contrib import admin
from django.urls import include, path
urlpatterns = [
    path('', include('first.urls')), # first 앱의 urls.py 에 연결
    path('admin/', admin.site.urls),
]
  • URL 맵핑 규칙
  1. 일치하는 문자열 : 'select/', 'select/10/' 와 같이 url 지정
  2. 변수화 : < path converter : name > 사용
  urlpatterns = [
    path('articles/2003/', views.special_case_2003),
    path('articles/<int:year>/', views.year_archive),
    path('articles/<int:year>/<int:month>/', views.month_archive),
    path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),
  ] # slug: 하이픈, 언더스코어를 포함한 영숫자 문자열

3 . 정규표현식 : (?P< name >Pattern) 사용

urlpatterns = [
    re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
    re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),
    re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<slug>[\w-]+)/$', views.article_detail),
]

Templates

장고 템플릿을 사용해서 html 파일과 views.py를 연동해서 현재 시각을 띄워 보고, 숫자의 홀짝도 확인하고, 숫자 리스트도 출력해보자! 이것저것... 그냥 다 해보자!!

여러 앱의 templates 폴더끼리의 혼동을 피하기 위해
각 웹앱의 templates 폴더 > app name 폴더 > html 파일들 경로로 저장

먼저, 템플릿 파일 인식을 위해 웹앱을 Settings.py의 INSTALLED_APPS 에 추가하고 TIME_ZONE을 서울으로 변경한다.
⬇️ Settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'first', # 추가
]

TIME_ZONE = 'Asia/Seoul'

⬇️ views.py

from django.shortcuts import render
from datetime import datetime


def index(request):
    now = datetime.now()
    context = {
        'current_date': now # 현재 시각을 context에 넣어 보내준다
    }
    return render(request, 'first/index.html', context)


def select(request):
    context = {'number':4}
    return render(request, 'first/select.html', context)


def result(request):
    context = {'numbers':[1, 2, 3, 4, 5, 6]}
    return render(request, 'first/result.html', context)

⬇️ urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name="index"),
    path('select/', views.select, name="select"),
    path('result/', views.result, name="result"),
]

  • block 이용하기
    base.html 파일에 기본 레이아웃을 지정하고,
    {% block content %} 와 {% endblock %} 사이만 갈아끼워주면 편하다!
    base.html을 제외한 템플릿 파일의 첫줄에서는 extends 블록에다
    어떤 파일을 이어서 렌더링할지 지정해주어야 한다.

⬇️ base.html

<html>
    <head>
        <meta charset="utf-8">
        <title>템플릿 테스트</title>
    </head>
    <body>
        {% block content %}
        {% endblock %}
    </body>
</html>

⬇️ index.html

{% extends 'first/base.html' %}
{% block content %}
        <h2>지금 시간은?</h2>
        <p>{{ current_date|date:"Y년 m월 d일 H시 i분 s초" }}</p>
        <a href="{% url 'select' %}">시작하기!</a> <!-- name으로 url 선택-->
{% endblock %}

⬇️ select.html

{% extends 'first/base.html' %}
{% block content %}
<p>
	{% if number|divisibleby:2 %} 
		짝수입니다. # context로 넘어온 number가 4이므로 출력
	{% else %}
		홀수입니다.
	{% endif %} 	<!--장고에서 if문은 endif로 따로 닫는 부분이 있어야 한다.
			나머지 연산자가 대신 장고에서 제공하는 divisibleby 필터를 사용-->
</p>
<p>
	<a href="{% url 'result' %}"><button>숫자 리스트 뽑기</button></a>
</p>
{% endblock %}

⬇️ result.html

{% extends 'first/base.html' %}
{% block content %}
<ul>
	{% for num in numbers %}
		<li>{{ num }}</li>
	{% endfor %}
</ul>
{% endblock %}

Static

여러 앱의 static 폴더끼리의 혼동을 피하기 위해
각 웹앱의 static 폴더 > app name 폴더 > static 파일들 경로로 저장

먼저, static 파일의 위치를 수정한다.

⬇️ Settings.py

STATIC_URL = '/static/'

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

{% load static %} 코드를 추가해서 장고 스태틱 모듈을 불러온 후,
{% static 'app name/static name' %} 문법으로 스태틱을 불러올 수 있다.

1 . 이미지
⬇️ index.html에 image.jpg 추가

{% extends 'first/base.html' %}
{% load static %}
{% block content %}
        <h2>지금 시간은?</h2>
        <img src="{% static 'first/image.jpg' %}" alt="시계">
        <p>현재 시각: {{ current_date|date:"Y년 m월 d일 H시 i분 s초" }}</p>
        <a href="{% url 'select' %}">시작하기!</a>
{% endblock %}

2 . CSS, JS

⬇️ 전체적으로 사용될 styles.css

body {
    text-align:center;
}

⬇️ base.html에 스태틱 모듈 불러오고 CSS 입히기

{% load static %}
<html>
    <head>
        <meta charset="utf-8">
        <title>로또 번호</title>
        <link rel="stylesheet" type="text/css" href="{% static 'first/styles.css' %}">
    </head>
    <body>
        {% block content %}
        {% endblock %}
    </body>
</html>

로또 추첨 프로그램

  • views.py
from django.shortcuts import render
from datetime import datetime
import random # 랜덤하게 뒤섞기 위해 임포트


def index(request):
    now = datetime.now()
    context = {
        'current_date': now
    }
    return render(request, 'first/index.html', context)
    
    
def select(request):
    context = {}
    return render(request, 'first/select.html', context)


def result(request):
    chosen = int(request.GET['number'])

    results = []
    # 만약 수가 범위를 초과하지 않으면 결과 값에 미리 선택한 수를 넣는다.
    if chosen >= 1 and chosen <= 45:
        results.append(chosen)

    # 값을 꺼낼 박스를 마련한다.
    box = []
    for i in range(0, 45):
        if chosen != i+1:
            box.append(i+1)

    # 랜덤하게 뒤섞는다.
    random.shuffle(box)

    # results 개수가 6개가 될 때 까지 값을 하나씩 꺼낸다.
    while len(results) < 6:
        results.append(box.pop())

    context = {'numbers':results}
    return render(request, 'first/result.html', context)

⬇️ select.html

{% extends 'first/base.html' %}
{% block content %}
<p>수를 하나 입력해주세요.</p>
<form action="{% url 'result' %}" method="get">
    <input type="number" name="number"/>
    <!-- 사용자가 입력할 숫자 데이터에 number라는 이름을 준다. -->
    <button type="submit">결과보기</button>
</form>
{% endblock %}

⬇️ result.html

{% extends 'first/base.html' %}
{% load static %}
{% block content %}
    <h3>추천 번호는 다음과 같습니다.</h3>
    <div style="text-align:left;">
        <ul>
            {% for num in numbers %}
            <li>{{ num }}</li>
            {% endfor %}
        </ul>
    </div>
{% endblock %}

profile
wanderlust

0개의 댓글