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

*아주중요 Django - HttpResponseRedirect(리다이렉트)

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

# 첫번째 파일

challenges > views.py

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

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):    
    months = list(monthly_challenges.keys())

    if month > len(months):
        return HttpResponseNotFound('Invalid month')
    # -1를 해주는 이유는 기본적으로 리스트 인덱스는 0 부터 시작되기 때문에 0을 입력했을때 1월이 나오게 하려고
    # 내 생각엔 +1를 해줘야할 것같은데 왜 작동이 될까?
    redirect_month = months[month - 1]
    return HttpResponseRedirect('/challenges/' + redirect_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'))    
]