> For the complete documentation index, see [llms.txt](https://dahye-jeong.gitbook.io/django/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dahye-jeong.gitbook.io/django/basic/2019-03-06-view.md).

# Django View & URL (1)

## View

여기서 View는 다른 MVC Framework에서 말하는 Controller와 비슷한 역할을 한다. 즉, 애플리케이션의 **로직**을 넣는 곳이다. 모델에서 필요한 정보를 받아와 template에 전달하는 역할을 한다.

* `app/view.py`

```python
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

```python
from django.urls import path

from . import views

urlpatterns = [
    # ex: /polls/
    path('', views.index, name='index'),
]
```

### project/urls.py

최상위 URLconf(프로젝트 생성시 생긴 `urls.py`)에서 애플리케이션의 url을 바라보게 설정한다.

```python
from django.contrib import admin
from django.urls import include,path

urlpatterns = [
        path('app/', include('app.urls')),
    path('admin/', admin.site.urls),
]
```

```python
"""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 설정에는 아무 경로에 연결하더라도 작동한다.

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