๐ View ๋?
1๊ฐ์ HTTP ์์ฒญ์ ๋ํด์ 1๊ฐ์ ๋ทฐ๊ฐ ํธ์ถ ๋๋ค. (urls.py/urlpatterns ๋ฆฌ์คํธ์ ๋งคํ๋ ํธ์ถ ๊ฐ๋ฅํ ๊ฐ์ฒด)
์น ํด๋ผ์ด์ธํธ๋ก๋ถํฐ HTTP ์์ฒญ์ ์ฒ๋ฆฌํ๋ฉฐ ํฌ๊ฒ ํจ์, ํด๋์ค ๊ธฐ๋ฐ ๋ทฐ ์ด๋ ๊ฒ 2๊ฐ์ง๊ฐ ์กด์ฌํ๋ค.
๐ View ํธ์ถ ์ ์ธ์
View ํธ์ถ์
๐ 1๋ฒ์งธ ์ธ์ : HttpRequest ๊ฐ์ฒด ์ ๋ฌ
ํ์ฌ ์์ฒญ์ ๋ํ ๋ชจ๋ ๋ด์ญ์ ๋ด๊ณ ์์
๐ 2๋ฒ์งธ ์ธ์ : ํ์ฌ ์์ฒญ์ URL๋ก๋ถํฐ Capture๋ ๋ฌธ์์ด๋ค
url/re_path๋ฅผ ํตํ ์ฒ๋ฆฌ์์๋ ๋ชจ๋ ์ธ์๋ str ํ์ ์ผ๋ก ์ ๋ฌ๋๋ฉฐ, path๋ฅผ ํตํ ์ฒ๋ฆฌ์์๋ Converter์ to_python์ ๋ง๊ฒ ๋ณํ๋ ๊ฐ์ด ์ธ์๋ก ์ ๋ฌ๋๋ค.
๐ View ํธ์ถ ์ ๋ฆฌํด ๊ฐ
ํํ HttpResponse ๊ฐ์ฒด๋ฅผ ๋ฆฌํดํ์ฌ์ผ ํ๋ค. ์ฅ๊ณ Mideeleware์์๋ ๋ทฐ์์ HttpResponse ๊ฐ์ฒด๋ฅผ ๋ฆฌํด ํ์ง ์์ผ๋ฉด ์ค๋ฅ๋ฅผ ๋ฐ์์ํจ๋ค.
๐ HttpRequest์ HttpResponse ์์
from django.http import HttpRequest, HttpResponse
def index(request: HttpRequest)->HttpResponse: # Viewํจ์
# ์ฃผ์ request ์์ฑ
request.method # 'GET', 'POST', etc.
request.META
request.GET, request.POST, request.FILES, request.body
content = '''
<html>…</html>
''' # ๋ฌธ์์ด ํน์ ์ด๋ฏธ์ง, ๊ฐ์ข
ํ์ผ ๋ฑ
response = HttpResponse(content)
response.write(content) # response -> file-like object
response['Custom-Header'] = 'Custom Header Value'
return response
๐ get_object_or_404 ํจ์ ์ฌ์ฉํ๊ธฐ
์ผ๋ฐ์ ์ผ๋ก DB์ ์๋ ๊ณณ์ queryset ์ผ๋ก ์ ๊ทผํ๊ฒ ๋๋ฉด HTTP ์ํ์ฝ๋๋ก 500์ ๋ฐํ ๋ฐ๊ฒ ๋๋๋ฐ, ํด๋น ๋ถ๋ถ์ ์๋ฒ ์ค๋ฅ๊ฐ ์๋ DB์ ๋ฐ์ดํฐ๊ฐ ์์์ผ๋ก 404 ์ํ์ฝ๋๋ฅผ ๋ฐํํ์ฌ์ผ ํ๋ค. ํด๋น ๋ถ๋ถ์ ํด์์์ผ์ฃผ๋ ๊ฒ์ด get_object_or_404 ํจ์์ด๋ค.
views.py
from django.shortcuts import get_object_or_404, render
def post_detail(request, id):
post = get_object_or_404(Post, id=id)
return render(request, 'blog/post_detail.html', {
'post': post,
})
def article_detail(request, id):
article = get_object_or_404(Article, id=id)
return render(request, 'blog/article_detail.html', {
'article': article,
})
urls.py
urlpatterns = [
path('post/<int:id>/', post_detail),
path('article/<int:id>/', article_detail),
]
์์ post/100 ์ ๊ทผ์ ํ๋ค๋ฉด ๋ค์๊ณผ ๊ฐ์ ์๋ฌ๊ฐ ๋จ๊ฒ ๋๋ค.
ํด๋น ์ฒ๋ฆฌ๋ฅผ ํ์ง ์๋๋ค๋ฉด ๋ค์๊ณผ ๊ฐ์ ์๋ฌ๊ฐ ๋จ๊ฒ ๋๋ค .
'FrameWork > Django' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
mark_safe์ ํตํด Admin ํ์ด์ง์์ ์ด๋ฏธ์ง๋ฅผ ํํํ๋ ๋ฐฉ๋ฒ (0) | 2023.03.05 |
---|---|
ERROR : django.db.utils.OperationalError: no such table ์ค๋ฅ ํด๊ฒฐ (0) | 2023.02.19 |
[Django] ๊ด๊ณ๋ฅผ ํํํ๋ Model Field (0) | 2023.02.08 |
[Django] Model ๊ฐ์ฒด ์กฐํํ๊ธฐ (0) | 2023.02.08 |
[Django] shell ์ฌ์ฉํ๊ธฐ (0) | 2023.02.08 |