How To Make A Website With Python And Django

Django web project consists of applications, and each Django web project can contains multiple applications. This article will tell you how to create and add Django application in web project. All the operation is implemented in a virtual environment. Please read How To Install Python Django In Virtual Environment first if you do not know.

1. Example Overview.

  1. The working folder in this example is virtualenv.
  2. my_env is just one virtual environment folder that i created.
  3. The my_django_project folder is the Django web project folder, and it contains one project settings folder my_django_project and one application folder to_do_list.
  4. The most important files in my_django_project / my_django_project folder are ( contains the web project configuration settings data, such as template file directory) and ( contains the web project request url path to each application’s mappings.).

Next we will tell you how to implement all this step by step.

django web application file structure in virtual environment new

2. Go Into Python Virtual Environment.

  1. CD into the working directory.
    $cd /Users/....../virtualenv
  2. Run source my_env/bin/activate to dive into the virtual environment.

    $ source my_env/bin/activate

3. Create Django Web Application.

  1. Run below command in the python virtual environment to create to_do_list application.
    (my_env) 192:my_django_project $ python startapp to_do_list
  2. After above step, the to_do_list folder is created in current folder, and the most important files has been added in the to_do_list folder are, and

4. Define Django Application Model.

4.1 Define App Model.

The app’s file contains all the app model class definition. A model class is mapped to a database table. And the class attribute map to the table’s column. So open the file in an editor and add below code in it. For convenience, i use eclipse PyDev plugin to edit the file, it is simple and efficient. Please read How To Run Python In Eclipse With PyDev to learn more.

from django.db import models
# Create your models here.
# This class maps to a table to_do_list_ToDo, the table name start with the app name.
class ToDo(models.Model):
    # Maps to to_do_things table column.
    to_do_things = models.CharField(max_length=1000)

    # Maps to create_date table column.
    create_date = models.DateTimeField(auto_now_add=True)

    # Maps to handle_date table column.
    handle_date = models.DateTimeField()
    def __str__(self):
        ''' Return this model string value. '''
        return self.to_do_things

use eclipse pydev to edit django app model file

4.2 Activate App Model.

After create the app model class, you need to add to_do_list app in my_django_project/my_django_project/ file to activate to_do_list app and use the model.

  1. Open file.
  2. Add to_do_list app in INSTALLED_APPS section.
         # Below is my app.

5. Create Django Model Mapped Table In Project SQLite Database.

  1. CD into the Django web project folder virtualenv / my_django_project.

    $ cd my_django_project
  2.  Create table to_do_list_todo in my_django_project SQLite database file ( my_django_project / db.sqlite3 ) with following command.
    (my_env) 192:my_django_project $ python makemigrations to_do_list
    Migrations for 'to_do_list':
        - Create model ToDo
    (my_env) 192:my_django_project $ python migrate
    Operations to perform:
      Apply all migrations: admin, auth, contenttypes, sessions, to_do_list
    Running migrations:
      Applying to_do_list.0001_initial... OK
  3. Use SQLiteStudio to open the db.sqlite3 file, you can see the table has been created.  Please read How To Install SQLite3 On Mac to learn how to use SQLite Studio.
    create a sqlite db table by django model

6. Register ToDo Model In Django Admin Site.

Open the virtualenv / my_django_project / to_do_list / file, and add below code in it.

from django.contrib import admin
# Import the model we defined in
from to_do_list.models import ToDo

# Register the ToDo model class to the admin site.

Now open browser and browse admin url http://localhost:8000/admin/, there add a new section TO_DO_LIST in the dashboard, you can manage your custom models in this section.

django admin page custom model section

Click Add link in the TO_DO_LIST section to add a new ToDo object as below picture.

django admin site add new model

When you click the Save button, the ToDo object has been added in the list, and the data is also inserted into the SQLite database table to_do_list_todo.

7. Mapping Urls.

When user request a url, Django will invoke a related python function predefined in application/ (to_do_list/ )  file.  There are two file.

  1. Web project level ( my_django_project/my_django_project/ ). This file contains request url to application file mappings, you can see them in later chapter.
  2. Application level ( my_django_project/to_do_list/, you should create this file by hand. This file contains url path to view function mappings in this application.

django project and app urls

7.1 Create Django Application Url Mapping File.

Create a file in to_do_list directory, and input below code in it. The urlpatterns variable in below code is a list of page url and python function mapping configuration.

from django.urls import path
# import views from local directory.
from . import views

urlpatterns = [

    # When user request home page http://localhost:8000/to_do, it will invoke the home function defined in
    path('', views.home, name='home'),

    # The first parameter is the url path.
    # The second parameter is the response function defined in file. 
    # The third parameter is the url name which will be used in html file url tag.
    # For example, in html code {% url 'to_do_list:to_do_list' %} will be mapped to url http://localhost:8000/to_do/list_all
    path('list_all', views.to_do_list, name='to_do_list'),
    # <id> is a placeholder that will be replaced with the real record id.
    path('show_detail/<id>/', views.to_do_detail, name='to_do_detail'),

7.2 Add Django App Urls Mapping File In Project Urls Mapping File.

To easily manage different Django app url mappings, we can create url mapping file for each Django app, and then add all those app url mapping files in project url mapping files.

So edit the my_django_project/my_django_project/ file with below content.

from django.contrib import admin
from django.urls import include, path
from django.conf.urls import url

urlpatterns = [

    # When request http://localhost:8000/admin/, it will use url mappings defined in file

    # When request http://localhost:8000/to_do, it will use url mappings defined in file
    # The include function must contains a tuple and a namespace key value pair. 
    # The tuple first element is the app urls mapping file, the second element is the application name.
    # If do not provide the application name, it will throw Specifying a namespace in include() without providing an app_name is not supported error.
    url('^to_do/', include(('to_do_list.urls','to_do_list'), namespace='to_do_list'))

8. Define View Function.

Now open virtualenv/my_django_project/to_do_list/ file and input below code.

from django.shortcuts import render
# Import ToDo model class defined in current file.
from .models import ToDo

import os

# Calculate django application execute directory path.
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))

# This function will return and render the home page when url is http://localhost:8000/to_do/.
def home(request):
    # Get the index template file absolute path.
    index_file_path = PROJECT_PATH + '/pages/home.html'

    # Return the index file to client.
    return render(request, index_file_path)

# This function will display todos in a list page the request url is http://localhost:8000/to_do/list_all.
def to_do_list(request):
    # Get all todos model object order by handle_date column.
    todos = ToDo.objects.order_by('handle_date')

    # Add the todos list in Django context.
    context = {'todos' : todos}

    # Get the list page absolute path. 
    to_do_list_file_path = PROJECT_PATH + '/pages/list.html'

    # Render and return to the list page.
    return render(request, to_do_list_file_path, context)

# Display the todo detail information in web page. The input parameter is todo id. The request url is http://localhost:8000/to_do/show_detail/3/.
def to_do_detail(request, id):

    # Get todo object by id.
    todo = ToDo.objects.get(id=id)

    # Set the todo object in context.
    context = {'todo' : todo}

    # Get todo detail page absolute file path.
    to_do_detail_file_path = PROJECT_PATH + '/pages/detail.html'

    # Return the todo detail page.
    return render(request, to_do_detail_file_path, context)

9. Create Template.

In step 8, you can see some html files are used in python function. These html files are called template file. There are four html template files in this example. Before introduce them, let us look at a video demo about this example. When you click links in the page, it will show related pages.

django web site template files example

9.1 base.html

This is the parent template file, other files will inherit from this file. It contains the navigation link and a block content placeholder. So all this file’s child template files will contains navigation links.

<!-- The url tag's parameter format is app_name:url_mapping_name(defined in app's file.) -->
<a href="{% url 'to_do_list:home' %}">Home Page</a>
<a href="{% url 'to_do_list:to_do_list' %}" style="margin-left:10px">List To Dos</a>
{% block content %}{% endblock content%}

9.2 home.html

<!DOCTYPE html>
<meta charset="UTF-8">
<title>Home Page</title>
<!-- extends the parent template file -->
{% extends "to_do_list/pages/base.html" %}
{% block content %}
This is the to do list web app home page.
{% endblock content%}

9.3 list.html

<!DOCTYPE html>
<meta charset="UTF-8">
<title>To Do List Page</title>
{% extends "to_do_list/pages/base.html" %}
{% block content %}
    <p>All Todos List</p>
        {% for todo in todos %}
            <li><a href="{% url 'to_do_list:to_do_detail' %}">{{todo}}</a></li>
        {% empty %}
            <li>No todos have been added yet.</li>
        {% endfor%}
{% endblock content%}

9.4 detail.html

<!DOCTYPE html>
<meta charset="UTF-8">
<title>To Do Detail Page</title>
{% extends "to_do_list/pages/base.html" %}
{% block content %}
        <li>Creation Date : {{todo.create_date}}</li>
        <li>Handle Date : {{todo.handle_date}}</li>
{% endblock content%}

9.5 Fix TemplateDoesNotExist Error.

When you browse web page in above example, you may meet Template Does Not Exist error like below.

django template does not exist error

This means Django can not find the template file, because the template directory is not configured correctly in my_django_project/my_django_project/ file. Follow below steps to fix it.

  1. Open file.
  2. Edit TEMPLATES / DIRS value to either the template file absolute path ( Django will find the template files in this path directly ) or an empty string like below '' ( In this case, you need to calculate the project path in the source code to get html template file absolute directory like above section 8).
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
             # DIRS can contains the absolute template file directory path.
             #'DIRS': ['/Users/zhaosong/Documents/WorkSpace/'],
             # Or the DIRS at least contains one empty string, otherwise the django system will throw TemplateDoesNotExist error. This is a bug of Django code.
             'DIRS': [''],
             'APP_DIRS': True,
                    'OPTIONS': {
                        'context_processors': [
  3. Now start the django web server and run the example as in the video.

1 thought on “How To Make A Website With Python And Django”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.