Django View & URL (1)
View
์ฌ๊ธฐ์ View๋ ๋ค๋ฅธ MVC Framework์์ ๋งํ๋ Controller์ ๋น์ทํ ์ญํ ์ ํ๋ค. ์ฆ, ์ ํ๋ฆฌ์ผ์ด์ ์ ๋ก์ง์ ๋ฃ๋ ๊ณณ์ด๋ค. ๋ชจ๋ธ์์ ํ์ํ ์ ๋ณด๋ฅผ ๋ฐ์์ template์ ์ ๋ฌํ๋ ์ญํ ์ ํ๋ค.
app/view.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world")
๊ฐ์ฅ ๊ฐ๋จํ ํํ์ view์ด๋ค. View๋ฅผ ํธ์ถํ๊ธฐ ์ํด์ URLconf๋ฅผ ์ด์ฉํด ์ฐ๊ฒฐํ๋ค.
Url
URLconf๋ฅผ ์์ฑํ๊ธฐ ์ํด์ app์ urls.py
ํ์ผ์ ์์ฑํ๋ค.
app
โโโ __init__.py
โโโ admin.py
โโโ apps.py
โโโ migrations
โ โโโ __init__.py
โโโ models.py
โโโ tests.py
โโโ urls.py
โโโ views.py
app/urls.py
from django.urls import path
from . import views
urlpatterns = [
# ex: /polls/
path('', views.index, name='index'),
]
project/urls.py
์ต์์ URLconf(ํ๋ก์ ํธ ์์ฑ์ ์๊ธด urls.py
)์์ ์ ํ๋ฆฌ์ผ์ด์
์ url์ ๋ฐ๋ผ๋ณด๊ฒ ์ค์ ํ๋ค.
from django.contrib import admin
from django.urls import include,path
urlpatterns = [
path('app/', include('app.urls')),
path('admin/', admin.site.urls),
]
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.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'))
"""
์ฃผ์์ผ๋ก urlpatterns์ ๋ํ ์ค๋ช ์ด ์๋ค.
Include()
: ๋ค๋ฅธ URLconf๋ฅผ ์ฐธ์กฐํ ์ ์๋๋ก ํ๋ค.path('์ฌ์ฉ์์ง์ ๊ฒฝ๋ก', include(url Conf module))
๋ค์๊ณผ ๊ฐ์ด urlConf ๋ชจ๋์ด ์กด์ฌํ๋ฉด ์์ path ์ค์ ์๋ ์๋ฌด ๊ฒฝ๋ก์ ์ฐ๊ฒฐํ๋๋ผ๋ ์๋ํ๋ค.
$ python manage.py runserver
์๋ฒ๋ฅผ ์คํ์ํจ ํ http://localhost:8000/app/
์ฐ๊ฒฐํ ๊ฒฝ๋ก์ ๋ค์ด๊ฐ๋ฉด View์์ ์ค์ ํ ํ๋ฉด์ด ๋์ค๋ ๊ฒ์ ํ์ธํ ์ ์๋ค.
path()
path(route, view,kwargs=None, name=None)
route : URL ํจํด์ ๊ฐ์ง ๋ฌธ์์ด์ด๋ค. urlpatterns ์ ์ฒซ๋ฒ์งธ ํจํด๋ถํฐ ์์ํด, ์ผ์นํ๋ ํจํด์ ์ฐพ์ ๋๊น์ง ์์ฒญ๋ url์ ๊ฐ ํจํด์ ์์๋๋ก ๋น๊ตํ๋ค.
view : ์ผ์นํ๋ ํจํด์ ์ฐพ์ผ๋ฉด HttpRequest ๊ฐ์ฒด๋ฅผ ์ฒซ๋ฒ์งธ ์ธ์๋ก ํ๊ณ , view ํจ์๋ฅผ ํธ์ถํ๋ค.
name : URL์ ์ด๋ฆ์ ์ง์ผ๋ฉด, ํ ํ๋ฆฟ์ ํฌํจํ ์ฅ๊ณ ์ด๋์์๋ ๋ช ํํ๊ฒ ์ฐธ์กฐํ ์ ์๋ค.
Last updated
Was this helpful?