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