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