In Django making web pages consists of three stages: defining URLs, writing views, and writing templates. First, you must define patterns for URLs. A URL pattern describes the way the URL is laid out and tells Django what to look for when matching a browser request with a site URL so it knows which page to return.
Each URL then maps to a particular view—the view function retrieves and processes the data needed for that page. The view function often calls a template, which builds a page that a browser can read. It's better to make a home page for our Pollsite and see how the three stages I just mentioned actually works.
We request pages by entering URLs into a browser and clicking links, so we’ll need to decide what URLs are needed in our project. The home page URL is first: it’s the base URL people use to access the project. At the moment, the base URL, http://localhost:8000/, returns the default Django site that lets us know the project was set up correctly. We’ll change this by mapping the base URL to Pollsite’s home page.
From C:\Projects\PollSite\Poll_Opinion open the urls.py file whose content is shown below:
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
In this urls.py file, which represents the project as a whole, the urlpatterns variable includes sets of URLs from the apps in the project. The code in the path()method includes the module admin.site.urls, which defines all the URLs that can be requested from the admin site. Here we'll add the code to our home page as shown below:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('polls.urls')),
]
Now we need to make a second urls.py file in the C:\Projects\PollSite\polls folder and add the following code to it:
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
# Home page
path('', views.IndexView.as_view(), name='index'),
]
We import path from the django.urls module needed to map the urls to views. We also import the views module ; the dot tells Python to import views from the same directory as the current urls.py module. The variable urlpatterns in this module is a list of individual pages that can be requested from the Polls app.
The actual URL pattern is a call to the path() function, which takes three arguments. The first is a regular expression. Django will look for a regular expression in urlpatterns that matches the requested URL string. Therefore, a regular expression will define the pattern that Django can look for.
In its entirety, this expression tells Python to look for a URL with nothing between the beginning and end of the URL. Python ignores the base URL for the project (http://localhost:8000/), so an empty regular expression matches the base URL. Any other URL will not match this expression, and Django will return an error page if the URL requested doesn’t match any existing URL patterns.
The second argument in path() specifies which view function to call. When a requested URL matches the regular expression, Django will call views.index (we’ll write this view function soon).
The third argument provides the name index for this URL pattern so we can refer to it in other sections of the code. Whenever we want to provide a link to the home page, we’ll use this name instead of writing out a URL.
Out of the three stages we mentioned in the beginning of this post we have completed the first stage, now we'll move on to the second stage which is writing a view function. A view function takes in information from a request, prepares the data needed to generate a page, and then sends the data back to the browser, often by using a template that defines what the page will look like.
The file views.py in C:\Projects\PollSite\polls was generated automatically when we ran the command python manage.py startapp. Here’s what’s in views.py right now:
from django.shortcuts import render
# Create your views here.
Currently, this file just imports the render() function, which renders the response based on the data provided by views. The following code is how the view for the home page should be written:
from django.shortcuts import render
# Create your views here.
def index(request):
"""The home page for Learning Log"""
return render(request, 'polls/index.html')
When a URL request matches the pattern we just defined, Django will look for a function called index() in the views.py file. Django then passes the request object to this view function. In this case, we don’t need to process any data for the page, so the only code in the function is a call to render().
The render() function here uses two arguments—the original request object and a template it can use to build the page. Let’s write this template now which is the third and final stage to create a web page.
A template sets up the structure for a web page and defines what the page should look like, and Django fills in the relevant data each time the page is requested. A template allows us to access any data provided by the view. As for now our view for the home page provided no data, this template is fairly simple.
We need to create a directory structure first in the C:\Projects\PollSite\polls folder. Make a new folder called templates. Inside the templates folder, make another folder called polls. This sets up a structure that Django can interpret unambiguously, even in the context of a large project containing many individual apps. Inside the inner polls folder (C:\Projects\PollSite\polls\templates\polls), make a new file called index.html. Add the following code into that file:
<p>Poll Questions</p>
<p>Click on the question to take part in the Poll</p>
Now that our template is ready we have fulfilled the criteria for the web page creation. Now when we request the project’s base URL, http://localhost:8000/, we’ll see the page we just built instead of the default Django page. Django will take the requested URL, and that URL will match the pattern ' '; then Django will call the function views.index(), and this will render the page using the template contained in index.html. The resulting page should be as shown below:
We have just created our first webpage, the home page for our poll application. In our poll application, we’ll have the following four views:
Question “index” page – displays the latest few questions.
Question “detail” page – displays a question text, with no results but with a form to vote.
Question “results” page – displays results for a particular question.
Vote action – handles voting for a particular choice in a particular question.
In the coming posts we shall create each of these pages.
Each URL then maps to a particular view—the view function retrieves and processes the data needed for that page. The view function often calls a template, which builds a page that a browser can read. It's better to make a home page for our Pollsite and see how the three stages I just mentioned actually works.
We request pages by entering URLs into a browser and clicking links, so we’ll need to decide what URLs are needed in our project. The home page URL is first: it’s the base URL people use to access the project. At the moment, the base URL, http://localhost:8000/, returns the default Django site that lets us know the project was set up correctly. We’ll change this by mapping the base URL to Pollsite’s home page.
From C:\Projects\PollSite\Poll_Opinion open the urls.py file whose content is shown below:
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
In this urls.py file, which represents the project as a whole, the urlpatterns variable includes sets of URLs from the apps in the project. The code in the path()method includes the module admin.site.urls, which defines all the URLs that can be requested from the admin site. Here we'll add the code to our home page as shown below:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('polls.urls')),
]
Now we need to make a second urls.py file in the C:\Projects\PollSite\polls folder and add the following code to it:
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
# Home page
path('', views.IndexView.as_view(), name='index'),
]
We import path from the django.urls module needed to map the urls to views. We also import the views module ; the dot tells Python to import views from the same directory as the current urls.py module. The variable urlpatterns in this module is a list of individual pages that can be requested from the Polls app.
The actual URL pattern is a call to the path() function, which takes three arguments. The first is a regular expression. Django will look for a regular expression in urlpatterns that matches the requested URL string. Therefore, a regular expression will define the pattern that Django can look for.
In its entirety, this expression tells Python to look for a URL with nothing between the beginning and end of the URL. Python ignores the base URL for the project (http://localhost:8000/), so an empty regular expression matches the base URL. Any other URL will not match this expression, and Django will return an error page if the URL requested doesn’t match any existing URL patterns.
The second argument in path() specifies which view function to call. When a requested URL matches the regular expression, Django will call views.index (we’ll write this view function soon).
The third argument provides the name index for this URL pattern so we can refer to it in other sections of the code. Whenever we want to provide a link to the home page, we’ll use this name instead of writing out a URL.
Out of the three stages we mentioned in the beginning of this post we have completed the first stage, now we'll move on to the second stage which is writing a view function. A view function takes in information from a request, prepares the data needed to generate a page, and then sends the data back to the browser, often by using a template that defines what the page will look like.
The file views.py in C:\Projects\PollSite\polls was generated automatically when we ran the command python manage.py startapp. Here’s what’s in views.py right now:
from django.shortcuts import render
# Create your views here.
Currently, this file just imports the render() function, which renders the response based on the data provided by views. The following code is how the view for the home page should be written:
from django.shortcuts import render
# Create your views here.
def index(request):
"""The home page for Learning Log"""
return render(request, 'polls/index.html')
When a URL request matches the pattern we just defined, Django will look for a function called index() in the views.py file. Django then passes the request object to this view function. In this case, we don’t need to process any data for the page, so the only code in the function is a call to render().
The render() function here uses two arguments—the original request object and a template it can use to build the page. Let’s write this template now which is the third and final stage to create a web page.
A template sets up the structure for a web page and defines what the page should look like, and Django fills in the relevant data each time the page is requested. A template allows us to access any data provided by the view. As for now our view for the home page provided no data, this template is fairly simple.
We need to create a directory structure first in the C:\Projects\PollSite\polls folder. Make a new folder called templates. Inside the templates folder, make another folder called polls. This sets up a structure that Django can interpret unambiguously, even in the context of a large project containing many individual apps. Inside the inner polls folder (C:\Projects\PollSite\polls\templates\polls), make a new file called index.html. Add the following code into that file:
<p>Poll Questions</p>
<p>Click on the question to take part in the Poll</p>
Now that our template is ready we have fulfilled the criteria for the web page creation. Now when we request the project’s base URL, http://localhost:8000/, we’ll see the page we just built instead of the default Django page. Django will take the requested URL, and that URL will match the pattern ' '; then Django will call the function views.index(), and this will render the page using the template contained in index.html. The resulting page should be as shown below:
We have just created our first webpage, the home page for our poll application. In our poll application, we’ll have the following four views:
Question “index” page – displays the latest few questions.
Question “detail” page – displays a question text, with no results but with a form to vote.
Question “results” page – displays results for a particular question.
Vote action – handles voting for a particular choice in a particular question.
In the coming posts we shall create each of these pages.