diff --git a/first_django_app.md b/first_django_app.md index 09583d3..4431a6c 100644 --- a/first_django_app.md +++ b/first_django_app.md @@ -76,3 +76,67 @@ polls/ views.py ``` +## Write the first view + +### Step 1: Create a simple view of `polls` app + +modify `polls/views.py` as + +```python +from django.http import request +from django.shortcuts import render + +def index(request): + return HttpResponse("Hello, world. You're at the polls index") +``` + +* `def index(request):...` is the simplest view + +### Step 2: In `polls` app, map the URL to this view + +After creating a view, map it to a URL so we can call it. Create `polls/urls.py`, and setup mapping `urlpatterns` + +```python +from django.urls import path + +from . import views + +urlpatterns = [ + path('', views.index, name='index'), +] +``` + +### Step 3: Point the root URLconf for polls + +To point the root URLconf at `polls.urls` module: +1. In `mysite/urls.py` + 1. add import for `django.urls.inclue` + 2. insert a `include()` in `urlpatterns` list + +i.e. + +```python +from django.contrib import admin +from django.urls import include, path + +urlpatterns = [ + path('polls/', include('polls.urls')), + path('admin/', admin.site.urls), +] +``` + +#### django.urls.include() + +> django.urls.include(): A function that takes a full Python import path to another URLconf module that should be “included” in this place. + +* new imported `include()` function allows referencing other URLconfs. +* `'polls.urls'` is the package that we are using, hence `mysite` can connect to `polls` app + +#### path() + +Here `path()` function is passed **route** and **view**; two additional option available **kwargs**, and **name** + +* `path()` argument **route**: a string that contains a URL pattern. When Django processing a request, it starts at the first pattern in `urlpatterns` and go down the list, comparing requested URL against each pattern +* `path()` argument **view**: when Django finds a matching pattern, it calls specified view function (a `HttpRequest` obj as the 1st argument, and others captured values as keyword argument) +* `path()` argument **kwargs**: passed in a dictionary to the target view +* `path()` argument **name**: naming URL, so we can refer to it elsewhere. \ No newline at end of file