django
django
django
  • Introduction
  • Django Introduction
  • Basic
    • 환경설정
    • About Django
    • Start Django Project
    • Secret Key 관리하기
    • Settings 분리하기
    • Django App
    • Django View & URL (1)
    • Django Model
      • MySQL 연동
    • Django Admin
    • Django View & URL (2)
    • Django Template
    • Django Template & View & URL
    • Django Static
    • Django form
  • Advanced
    • Django Generic View
    • Django Automated Testing
    • Django Extenstion Template
    • Django Model Package
    • Django OpenSSL setting
  • REST framework
    • Rest API
    • Serializers
    • ViewSet
  • Error
    • 환경설정 zlib 오류발생
    • ModuleNotFoundError
  • 패키지
    • django-debug-toolbar
  • Vue.js 연동하기
Powered by GitBook
On this page
  • View
  • Url
  • app/urls.py
  • project/urls.py

Was this helpful?

  1. Basic

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에 이름을 지으면, 템플릿을 포함한 장고 어디에서든 명확하게 참조할 수 있다.

PreviousDjango AppNextDjango Model

Last updated 5 years ago

Was this helpful?