python manage.py startapp pages
Adding a page
Currently we see a placeholder page when we visit the Django project in the browser. As a wireframe for future additions, let’s create a minimal app in Django.
The app will serve a welcome page when visiting the root of our project and contain some styling. With the welcome page we can see if Django works correctly even when the debug mode is deactivated. With the added styling, we will see if static files are served correctly.
Create the app
The purpose of this app is to serve static pages – so we name it pages.
Create the pages app:
Add the pages app to INSTALLED_APPS
in the settings file:
INSTALLED_APPS = [
# Other installed apps like django.contrib.*
'pages',
]
Add welcome view
A basic view receives a request, handles it and returns a response. In this case we want to display a welcome page with a message.
Add welcome
function to pages/views.py
def welcome(request):
content = {
"welcome_msg": "Hello!",
}
template = "pages/welcome.html"
return render(request, template, content)
Add the welcome page template
The view currently tries to render a template that does not exist yet. To keep the modular structure of our project, we create it in a subdirectory of the pages app.
Create the subdirectory for pages templates and create the welcome template:
mkdir -p pages/templates/pages
touch pages/templates/pages/welcome.html
The repetition of the app name in the path of the template is to prevent confusion between templates of the same name in different apps. |
Add content to the welcome template:
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>djangoku</title>
<link rel="stylesheet" href="{% static 'css/pages.css' %}" type="text/css" />
</head>
<body>
<h1>{{welcome_msg}}</h1>
</body>
</html>
Add the CSS file
As you can see we referenced a css file that does not exist yet.
Create pages.css:
mkdir -p pages/static/css
touch pages/static/css/pages.css
Add basic styling to pages.css:
body {
background-color: ghost;
}
h1 {
text-align: center;
font-family: monospace;
}
Add urls
We now have a view that renders a template with styling.
But we have not defined, where Django should show this view.
Therefore need to define two url patterns.
One for telling the project that we want to serve the pages urls on root level.
The other for telling the pages app to serve our welcome view when the path is ""
.
Include pages.urls
to urlpatterns
of the main djangoku urls file:
from django.contrib import admin
from django.urls import include, path
# Do not forget to import `include` from django.urls
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('pages.urls'))
]
Create an urls file for the pages app:
touch pages/urls.py
Add welcome
path to urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.welcome, name='welcome'),
]
Commit the code
Now we can stage and commit our changes:
git add .
git commit -m "Add pages app 📔"