본문 바로가기

Python/Django

[Django] Django - (맛보기)Redirect

이번에는 Redirect에 대해서 알아보겠습니다.

 

 

  • /first_app/views.py - num_page_view 추가
from django.shortcuts import render
from django.http.response import HttpResponse, Http404, HttpResponseNotFound, HttpResponseRedirect

# Create your views here.
articles = {
    'sports':'Sport page~',
    'finance':'Finance page~',
    'politics':'Politics page~',
    'sports1':'Sport1 page1~',
}    

def news_view(request, topic):
    try:
        result = articles[topic]
        return HttpResponse(result)
    except:
        raise Http404('404 generic ERROR') # 404.html 만들어서 처리 예정임,

# domain.com/first_app/0 --> domain.com/first_app/finance
def num_page_view(request, num_page):
    try:
        print(f'{num_page}')
        topics_list = list(articles.keys()) # ['sports','finance','politics']
        topic = topics_list[num_page]
        print(f'{topics_list}   {topic}')
        return HttpResponseRedirect(topic)
    except:
        raise Http404('404 generic ERROR') # 404.html 만들어서 처리 예정임,

 

 

  • /first_app/urls.py - path('<int:num_page>', views.num_page_view) 추가
from django.urls import path
from . import views

urlpatterns = [
    path('<int:num_page>', views.num_page_view),
    path('<str:topic>/', views.news_view),
    path('<int:num1>/<int:num2>', views.add_view),
]

 

 

  • 결과는 로그로 확인합니다.
0
['sports', 'finance', 'politics', 'sports1']   sports
[19/Oct/2022 15:07:13] "GET /first_app/0 HTTP/1.1" 302 0 ===> 처음주소
[19/Oct/2022 15:07:13] "GET /first_app/sports/ HTTP/1.1" 200 11 ===> redirect된 주소
1
['sports', 'finance', 'politics', 'sports1']   finance
[19/Oct/2022 15:07:18] "GET /first_app/1 HTTP/1.1" 302 0
[19/Oct/2022 15:07:18] "GET /first_app/finance/ HTTP/1.1" 200 13
2
['sports', 'finance', 'politics', 'sports1']   politics
[19/Oct/2022 15:07:21] "GET /first_app/2 HTTP/1.1" 302 0
[19/Oct/2022 15:07:21] "GET /first_app/politics/ HTTP/1.1" 200 14
3
['sports', 'finance', 'politics', 'sports1']   sports1
[19/Oct/2022 15:07:25] "GET /first_app/3 HTTP/1.1" 302 0
[19/Oct/2022 15:07:25] "GET /first_app/sports1/ HTTP/1.1" 200 13
4
Not Found: /first_app/4
[19/Oct/2022 15:07:28] "GET /first_app/4 HTTP/1.1" 404 2538