Skip to content

Commit b114128

Browse files
committed
Doc: Add new tutorial explaining the concept of applications and routs in django
1 parent 2969dbb commit b114128

File tree

2 files changed

+152
-4
lines changed

2 files changed

+152
-4
lines changed
Lines changed: 152 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
# Applications in Django
22

3-
The thinking behind Django is that we have a website project, which we have already created in [the previous tutorial](01_getting_started.md), and have multiple apps each doing its own thing. For example, we can have a blog section of the website, which is an app on its own, then we can have a store section which is an app as well. So, a single project can contain multiple apps.
3+
The thinking behind Django is that we have a website project, which we have already created in [the previous tutorial](01_getting_started.md), and have multiple apps each doing its own thing. For example, we can have a blog section of the website, which is an app on its own, then we can have a store section which is an app as well. So, a single project can contain multiple apps. In this tutorial, we are going to add a blog app within our project.
44

5-
If you would like to skip to a particular section in the entire Django tutorial, you can do so by clicking on any of the links below:
5+
For your reference, if you would like to skip to a particular section in the entire Django tutorial, you can do so by clicking on any of the links below:
66

77
- [Django Overview](00_overview.md)
88
- [Getting Started With Django](01_getting_started.md)
@@ -11,7 +11,7 @@ If you would like to skip to a particular section in the entire Django tutorial,
1111

1212
### Table of Contents
1313

14-
In this tutorial, we are going to add a blog app within our project.
14+
This article has the following sections:
1515

1616
- [Create an app](#create-an-app)
1717

@@ -20,9 +20,157 @@ In this tutorial, we are going to add a blog app within our project.
2020

2121
## Create An App
2222

23-
Ensure you are currently at the top-level directory of our project, where `manage.py` is located. From the terminal, run the following command:
23+
Ensure you are currently at the top-level directory of our project, where `manage.py` is located. From the terminal, run the following command to create a blog app:
2424

2525
```python
2626
(venv)$ python3 manage.py startapp blog
2727
```
2828

29+
You will notice that Django automatically creates a full app for us called `blog` with its own structure. The `tree` command can reveal this new structure:
30+
31+
```python
32+
(venv)$ tree
33+
34+
# Output
35+
36+
.
37+
├── blog
38+
│ ├── admin.py
39+
│ ├── apps.py
40+
│ ├── __init__.py
41+
│ ├── migrations
42+
│ │ └── __init__.py
43+
│ ├── models.py
44+
│ ├── tests.py
45+
│ └── views.py
46+
├── blog_app
47+
│ ├── asgi.py
48+
│ ├── __init__.py
49+
│ ├── __pycache__
50+
│ │ ├── __init__.cpython-38.pyc
51+
│ │ ├── settings.cpython-38.pyc
52+
│ │ ├── urls.cpython-38.pyc
53+
│ │ └── wsgi.cpython-38.pyc
54+
│ ├── settings.py
55+
│ ├── urls.py
56+
│ └── wsgi.py
57+
├── db.sqlite3
58+
└── manage.py
59+
```
60+
61+
It might be quite intimidating to know that we have a lot of project files to work with right out of the box, but let's start with a few of them to get the hang of it.
62+
63+
### Views
64+
65+
We shall begin by making changes to the `views` module of our `blog` app. What we want to do is to create a view function that will handle the traffic from the home page.
66+
67+
```python
68+
# blog/views.py
69+
70+
from django.shortcuts import render
71+
from django.http import HttpResponse
72+
73+
# Create your views here.
74+
def home(request):
75+
return HttpResponse('<h1>Blog home!</h1>')
76+
77+
```
78+
79+
By default, Django already imports `render` for us. This function is used to combine a template with a context dictionary and returns a HttpResponse object with the rendered text. It is a shortcut to the long function `django.template.loader.render_to_string`.
80+
81+
At this point, though, we are not going to use the `render` function. I have used the `HttpResponse` function to display a simple message whenever a user visits the home page. This function is used in Django to return a text response. Typically, every view function takes a `request` argument.
82+
83+
### URL Patterns
84+
85+
URL patterns are used to match requested URLS. Django runs through all available patterns in order and retrieves the first one that matches a requested URL. Once one of the URL patterns matches, Django imports and calls the given view function.
86+
87+
### Application URLs
88+
89+
Within our `blog` app directory, let us create a new module called `urls.py` which is similar to what we have in our root project folder.
90+
91+
```python
92+
(venv)$ touch blog/urls.py
93+
```
94+
95+
Let us update this module with the following code:
96+
97+
```python
98+
99+
# demo_project/blog/urls.py
100+
101+
from django.urls import path
102+
from . import views
103+
104+
105+
urlpatterns = [
106+
path('', views.home, name='blog-home'),
107+
]
108+
109+
```
110+
111+
Here, Django queries the `urls` module to look for the variable `urlpatterns`, which is a sequence. It runs through each item in the sequence in order (there is only one at the moment) and stops at the first one that matches the requested URL. The view function `home` is called from the `views` module. I have used the `.` (dot) to denote that both the `views` and the `urls` modules are located in the current app folder called `blog`. The first argument is an empty string to show that it is the home URL. I have also passed the `name` argument in order to assign a name to this pattern. Intentionally, I have named it `blog-home` instead of `home` because as the project grows, I am mostly likely to have multiple `home` functions for each app.
112+
113+
### Project URLs
114+
115+
To complete the setup process, we also need to update the `urls` module in the root project folder. This updated URL configuration will tell Django that upon request, the project should serve the requested resource found in the specified application.
116+
117+
```python
118+
119+
# demo_project/blog_app/urls.py
120+
121+
from django.contrib import admin
122+
from django.urls import path, include
123+
124+
125+
urlpatterns = [
126+
path('admin/', admin.site.urls),
127+
path('blog/', include('blog.urls')),
128+
]
129+
130+
```
131+
132+
Django will check all URL patterns in `blog_app.urls.py` to find any one that matches a request. Since we want to access the home page in our `blog` app, the request http://127.0.0.1:8000/blog will tell Django that it needs to serve the blog app. Thereafter, the application will redirect any further request to `blog.urls.py` for more processing.
133+
134+
As a sidenote, URLs in Django do not come with a preceeding slash. All URLS have a forward slash and it is therefore redundant to prepend them. However, Django URLs end with a slash.
135+
136+
To see the changes, let us start our django server by running:
137+
138+
```python
139+
(venv)$ python3 manage.py runserver
140+
```
141+
142+
Paste the URL http://127.0.0.1:8000 on the browser to access the application.
143+
144+
![Blog App](/02_django/images/02_application_and_routes/access_blog_app.gif)
145+
146+
Notice that no page is found once we paste the localhost link on our browser. This is because there is no matching URL for http://127.0.0.1:8000/. Appending `blog` to the URL serves as with the text "Blog home!". If we want the root of our website to be the home page, we need to leave the path to the blog's home page empty. So, instead of `path('blog/' include('blog.urls'))` we will have `path('', include('blog.urls'))`.
147+
148+
149+
### Additional Routes
150+
151+
To get a better grasp of how URLs work in Django, let us add one more view function to our `blog` app. Within the `views` module in the `blog` app, let us add a function that will handle the logic for the "About" page.
152+
153+
```python
154+
# demo_project/blog/views.py
155+
156+
# ...
157+
158+
def about(request):
159+
return HttpResponse('<h1>Blog about page!</h1>')
160+
```
161+
162+
Once the function is defined, we need to update the `blog.urls.py` file to point all requests for the about page to the `about()` view function.
163+
164+
```python
165+
# demo_project/blog/urls.py
166+
167+
# ...
168+
169+
urlpatterns = [
170+
# ...
171+
path('about/', views.about, name='blog-about'),
172+
]
173+
174+
```
175+
176+
That is it. When we go to the link http://127.0.0.1:8000/blog/about/ on our browser, we should be able to see the text "Blog about page".
Loading

0 commit comments

Comments
 (0)