WEB/Django prac

[Django prac][URL] Variable routing(str) 1

bay07 2024. 3. 14. 15:53

 

▷ Variable Routing 

URL 일부에 변수를 포함시키는 것

변수는 view 함수의 인자로 전달할 수 있다. 

 

<path_converter:variable_name>

path('articles/<int:num>/', views.detail)

path('hello/<str:name>/', views.greeting)


 

* 스켈레톤 코드 다운 (비공개)

https://blog.naver.com/bayleaf07/223383180892


1. URLs 작성하기

작성하기 전
작성한 후

더보기
"""
URL configuration for firstpjt project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/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
from articles import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
    path('dinner/', views.dinner),
    path('search/', views.search),
    path('throw/', views.throw),
    path('catch/', views.catch),
    # <> 에 문자열이 바뀌는 변수를 받을 것이다
    # 타입이 문자열이기 때문에 <str:> 이렇게 적기 
    # 변수의 이름이 name이기 때문에 <str:name> 이렇게 적기    
    # 변수 이름이 bear면 <str:bear> 이렇게 적으면 된다. 
    path('greeting/<str:name>/', views.greeting),
]

 

 


2. Views 작성하기

greeting 이라는 view 함수에서 name 이라는 값을 받아서

template에서 출력하는 것

 

context에는 url에서 넘어온 이름을 view함수의 인자로 받는다.

def greeting (request, name):

request 이후에 variable routing 변수들이 나온다

코드를 적기 전의 모습
코드를 적은 후

더보기
# 여기 주석 풀어주기
# foods 중에 랜덤으로 뽑아서 출력하려고
import random
from django.shortcuts import render


def index(request):
    context = {
        'name' : 'stella',
    }
    return render(request, 'articles/index.html', context)

def dinner(request):
    foods = [
        '사과',
        '딸기',
        '바나나',
        '감',
    ]
    picked = random.choice(foods)
    context = {
        'foods':foods,
        'picked':picked,
    }
    return render(request, 'articles/dinner.html', context)

def search(request):
    return render(request, 'articles/search.html')

def throw(request):
    return render(request, 'articles/throw.html')


def catch(request):
    
    message = request.GET.get('message')

    context = {
        'message' : message,
    }
    return render(request, 'articles/catch.html',context)

# context에는 url에서 넘어온 이름을 view함수의 인자로 받는다.
# def greeting (request, name): 이런 식으로 
# request 이후에 variable routing 변수들이 나온다

def greeting(request, name):
    context = {
        'name': name,
    }
    return render(request, 'articles/greeting.html',context)

 

3. greeting.html  만들고 작성하기

빈 파일 먼저 만들기
코드 적기

더보기
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <h1>Hello {{ name }}</h1>
</body>
</html>

 

4. 실행해보기 

일단 다 저장 

python manage.py runserver

 

http://127.0.0.1:8000/greeting/(내가 쓰고 싶은 이름)/

 

 

 


 

* 참고