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

*매우중요 Django - views파일에서 하나의 함수로 다중 urls 호출하기

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

views를 호출해 주기 위해서 3군데를 건드려줄 필요가 있었다.


# 첫번째 파일

challenges > views.py

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

# Create your views here.

def january(request):
    return HttpResponse('This is january')

def february(request):
    return HttpResponse('This is february')

def march(request):
    return HttpResponse('Learn Django for at least 20 minutes')

def monthly_challenge(request, month):
    challenge_text = None
    if month == 'january':
        challenge_text = 'Eat no meat for the entire month!'
    elif month == 'february':
        challenge_text = 'Walk for at least 20 minutes every day!'
    elif month == 'march':
        challenge_text = 'Learn Django for at least 20 minutes every day'
    else:
        return HttpResponseNotFound('This month is not suppoted!')
    # 성공했을때
    return HttpResponse(challenge_text)

# 두번째 파일

challenges > urls.py

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

urlpatterns = [
    path('<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'))    
]