본문 바로가기
개발일지/Django

*매우중요 Django - 딕셔너리(dict)로 함수 간결화 하여서 views 호출하기

by 개발에정착하고싶다 2022. 10. 7.

이번에도 파일은 3개다

하지만 특이 사항이 있다면, 두번째 파일의 <int:month>에 대한 실질적 기능에 대한 다룸은 다음 강의에서 다룬다.

따라서 <str:month> path만 있다고 가정하고 views.py (첫번째 파일)를 조작해 줬다고 보면 된다.


 

# 첫번째 파일

challenges > views.py

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseNotFound

monthly_challenges = {
    'january':'Eat no meat for the entire month!',
    'february': 'Walk for at least 20 minutes every day!',
    'march': 'Learn Django for at least 20 minutes every day',
    'april': 'Eat no meat for the entire month',
    'may': 'Walk for at least 20 minutes every day',
    'june': 'Learn Django for at least 20 minutes every day',
    'july': 'Eat no meat for the entire month',
    'august': 'Walk for at least 20 minutes every day',
    'september': 'Learn Django for at least 20 minutes every day',
    'october': 'Eat no meat for the entire month',
    'november' :'Walk for at least 20 minutes every day',
    'december' : 'Learn Django for at least 20 minutes every day'
}
# Create your views here.

def monthly_challenge_by_number(request, month):    
    return HttpResponse(month)

def monthly_challenge(request, month):
    try:
        challenge_text = monthly_challenges[month]
    except:
        return HttpResponseNotFound('This month is not supported')
    
    # 성공했을때
    return HttpResponse(challenge_text)

# 두번째 파일

challenges > urls.py

from django.urls import path
# 동일한 폴더 안에 있을때 .를 써준다.
# 현재의 상황에서는 views 파일에 있는 index 함수를 호출해오는 것이다.
from . import views

urlpatterns = [
    path('<int:month>', views.monthly_challenge_by_number),
    path('<str:month>', views.monthly_challenge)
]

# 세번째 파일

monthly_challenges > urls.py

"""monthly_challenges URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    # 특이한점은 경로를 붙일때, 파일의 확장자를 배제하고 urls.py를 urls로만 기입해야 작동한다는 것이다.
    path('challenges/', include('challenges.urls'))    
]