URL 주소가 비슷한게 여러개가 있다면 일일히 쳐야할까...?
urlpatterns = [
path('articles/1/', ...),
path('articles/2/', ...),
path('articles/3/', ...),
path('articles/4/', ...),
path('articles/5/', ...),
....
]
이런 번거로움을 덜기 위해 URL의 일부에 변수를 포함시키는 기능 = Variable Routing
Variable Routing
URL 일부에 변수를 포함시키는 것
이때, 변수는 view 함수의 인자로 전달 할 수 있다.
구조
<path_converter:variable_name>
- path converter란?
: URL 변수의 타입을 지정해 줌
(str, int등 5가지의 타입을 지원)
쓰는 방법
1. urls.py에서 경로를 추가해준다.
urlpatterns = [
path('hello/str:name/', views.greeting),
path('articles/int:num/',views.detail),
]
url주소에서 <str:name>
, <int:num>
부분이 변수, 즉 variable routing이 됨
2. views.py에서 함수를 정의해 준다.
def greeting(request, name):
context = {
'name' : name
}
return render(request, 'articles/greeting.html', context)
def detail(request, num):
context = {
'num' : num,
}
return render(request, 'articles/detail.html',context)
여기서, 함수의 인자로 name과 num을 받을 수 있다.
3. greeting.html과 detail.html을 작성해서 결과를 확인할 수 있다.
{% extends "base.html" %}
{% block content %}
<h1>안녕, {{name}}~!</h1>
{% endblock content %}
{% extends "base.html" %}
{% block content %}
<h1>여기는 {{num}}번 게시글 페이지입니다.</h1>
{% endblock content %}
'BackEnd > Django' 카테고리의 다른 글
[Django] Model과 Migrations (0) | 2023.09.14 |
---|---|
[Django] App URL (0) | 2023.09.14 |
[Django] form활용: throw & catch (0) | 2023.09.13 |
[Django] 요청과 응답(form) (0) | 2023.09.13 |
[Django] Template 상속 (0) | 2023.09.13 |
댓글