Skip to content

Latest commit

 

History

History
317 lines (220 loc) · 15.5 KB

File metadata and controls

317 lines (220 loc) · 15.5 KB

Getting Started with Django

In the early stage of web development, developers needed to write every page by hand. For example, for a news portal website, its HTML pages had to be changed every day. As the scale and size of the website grew, this way was definitely very bad. To solve this problem, developers thought of using programs to generate dynamic content for Web servers. In other words, dynamic content in web pages was no longer written by hand, but generated automatically by programs.

At the earliest time, this technology was called CGI. Of course, as time passed, CGI showed more and more problems, such as a lot of repeated boilerplate code and generally low performance. Then PHP, ASP, and JSP appeared one after another in the late 1990s. Usually, when we say a Web application, we mean an application that accesses network resources through a browser. Because browsers are common and easy to use, Web applications are convenient and simple to use, and they avoid the trouble of installing and updating applications. From the developer's point of view, they also do not need to care about what operating system the user uses, and do not even need to distinguish between PC and mobile.

Web Application Mechanism and Terms

The picture below shows us the workflow of a Web application. The terms involved are shown in the table below.

Term Meaning
URL / URI Uniform Resource Locator / Uniform Resource Identifier, the unique identifier of a network resource
Domain name An easy-to-remember string name corresponding to a Web server address
DNS Domain name resolution service, which can turn a domain name into the corresponding IP address
IP address The identity of a host on the network
HTTP HyperText Transfer Protocol, an application-level protocol built on TCP and the basis of World Wide Web data communication
Reverse proxy Receives requests from the client to the server, then returns the resources returned by the server to the client
Web server Accepts HTTP requests, then returns resources such as HTML files, plain text files, and images to the requester
Nginx A high-performance Web server, and it can also be used as a reverse proxy, load balancer, and HTTP cache

Note: Readers with experience may notice that many things are still missing from the picture above, such as reverse proxy servers, database servers, firewalls, and so on. Also, in actual project deployment, every node in the picture may be a cluster made of multiple nodes. Of course, if you do not understand these yet, that is fine. Just keep going, and we will explain them one by one later.

HTTP Protocol

Here we first spend some time talking about the HTTP protocol. HTTP is an application-level protocol built on top of TCP. It uses the reliable transmission service provided by TCP to exchange data in Web applications. According to Wikipedia, HTTP was originally designed to provide a way to publish and receive HTML pages, that is to say, this protocol is the carrier of data sent between the browser and the Web server.

An HTTP request typically contains:

  • request line
  • headers
  • blank line
  • optional body

An HTTP response typically contains:

  • status line
  • headers
  • blank line
  • body

The two pictures below are the HTTP request and response packets I captured when visiting Baidu's homepage while studying and working in the Key Laboratory of Network Communication Technology of Sichuan Province. Since the packet capture tool captures data that goes through the network adapter, we can clearly see protocol data from the physical link layer to the application layer.

HTTP request (request line + request headers + blank line + [message body]):

HTTP response (response line + response headers + blank line + message body):

Note: These two pictures were captured in the early morning of September 10, 2009. I hope these screenshots, which look like old yellowed photos, can help you understand what HTTP really looks like. Of course, if you do not have a professional packet capture tool, you can also use the "Developer Tools" provided by the browser to view the data format of HTTP requests and responses.

Django Overview

Python has many Web frameworks, more than its keywords. A so-called Web framework is infrastructure used to develop server-side Web applications. To say it more simply, it is a series of packaged modules and tools. In fact, even without a Web framework, we can still develop server-side Web applications through socket or CGI, but in commercial projects the cost and price of doing that are usually unacceptable. Through a Web framework, we can turn complexity into simplicity and reduce the work of creating, updating, and expanding applications. The frameworks include Django, Flask, Tornado, Sanic, Pyramid, Bottle, Web2py, web.py, and so on.

Django is without doubt the most representative heavyweight among the Python Web frameworks above. Developers can quickly develop reliable Web applications based on Django, because it reduces unnecessary cost in Web development, packages common design and development patterns, and supports the MVC architecture, which Django calls the MTV architecture.

Django uses the MTV pattern:

  • M: Model, representing data
  • T: Template, responsible for presentation
  • V: View, the logic that connects templates and models

MVC is an architecture that works everywhere in software-system development. It divides the components in a system into Model, View, and Controller, and in this way decouples model (data) and view (display). Since model and view are separated, a middleman is needed to connect them, and this role is played by the controller. Any software system with a little scale uses MVC architecture, or some other architecture evolved from MVC. In Django, we call it MTV. The M in MTV is the same as the M in MVC and represents the data model. T stands for the web template, the view that displays data. V stands for the view function. In Django, the view function and the Django framework itself together play the role of C in MVC.

Django was born in 2003. It grew out of a real project and was developed by the CMS team of an online news website under Lawrence Publishing Group. It was named after the Belgian gypsy jazz guitarist Django Reinhardt. Django was released as an open-source framework in the summer of 2005. Using Django, we can build fully functional websites in a short time, because it does those repetitive and boring tasks instead of the programmer, leaving the truly meaningful core business to the programmer. This is the best practice of the DRY idea.

Your First Django Project

  1. Check your Python version.

Different Django versions require different Python versions. For example:

  • Django 1.11 requires Python 2.7 or Python 3.4+
  • Django 2.2 requires Python 3.5+
  • Django 3.0 requires Python 3.6+

Check your interpreter:

python3 --version

You can also inspect it from Python itself:

import sys
sys.version
sys.version_info
  1. Install Django.
pip3 install -U pip
pip3 install django==2.2.13
  1. Create a project:
django-admin --version
django-admin startproject hellodjango
  1. Open the project in PyCharm or another IDE and create a virtual environment if needed.

Important project files:

  • hellodjango/__init__.py: marks the directory as a Python package
  • hellodjango/settings.py: project configuration
  • hellodjango/urls.py: URL routing
  • hellodjango/wsgi.py: WSGI entry point
  • manage.py: management script
  1. Install project dependencies inside the virtual environment if necessary:
pip install django==2.2.13
  1. Run the development server:
python manage.py runserver

Visit http://127.0.0.1:8000 in a browser.

Notes:

  • Django’s built-in server is only for development and testing.
  • Code changes are usually reloaded automatically.
  • You can inspect available management commands with python manage.py help.
  • The default server runs on port 8000, but you can specify another IP or port.

Configure Language and Time Zone

Django supports internationalization and localization. In settings.py, change:

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'

to:

LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Chongqing'

Refreshing the browser will show the localized Django welcome page.

Create Your Own App

If you want to build your own web application, you first need to create an "app" inside the Django project. A Django project can contain one or more apps.

  1. Run the command below in the PyCharm terminal to create an app named first.
python manage.py startapp first

Running that command creates a first directory with the following structure:

  • __init__.py: an empty file that tells Python this directory should be treated as a package
  • admin.py: used to register models so they can be managed in Django's built-in admin site
  • apps.py: the app configuration file
  • migrations: stores migration information related to models
  • models.py: stores the app's data models
  • tests.py: contains tests for the app
  • views.py: functions or classes that handle HTTP requests and return HTTP responses
  1. Modify the app's views.py file.
from django.http import HttpResponse


def show_index(request):
    return HttpResponse('<h1>Hello, Django!</h1>')
  1. Modify the Django project's urls.py file so the view function is mapped to a browser path.
from django.contrib import admin
from django.urls import path, include

from first.views import show_index

urlpatterns = [
    path('admin/', admin.site.urls),
    path('hello/', show_index),
]
  1. Run the project again and open http://127.0.0.1:8000/hello/ in your browser.

  2. The content above is still static, even though it is generated by Python code. If you want to generate dynamic content, you can change views.py as shown below.

from random import sample

from django.http import HttpResponse


def show_index(request):
    fruits = [
        'Apple', 'Orange', 'Pitaya', 'Durian', 'Waxberry', 'Blueberry',
        'Grape', 'Peach', 'Pear', 'Banana', 'Watermelon', 'Mango'
    ]
    selected_fruits = sample(fruits, 3)
    content = '<h3>Today\'s recommended fruits are:</h3>'
    content += '<hr>'
    content += '<ul>'
    for fruit in selected_fruits:
        content += f'<li>{fruit}</li>'
    content += '</ul>'
    return HttpResponse(content)
  1. Refresh the page and observe the result. Each refresh should show different content.

Using Templates

Generating HTML by string concatenation, as shown above, is not acceptable in real development. Frontend pages in real projects can be much more complex, and there is no practical way to build them by manually piecing strings together. To solve this problem, we prepare a template page in advance. In MTV terms, this is the T. A template page is an HTML page with placeholders and template instructions.

Django provides a convenience function named render to render templates. Rendering means replacing placeholders and template instructions with actual data. This is server-side rendering, meaning the server renders the page first and then sends it to the browser. In applications with heavy traffic, server-side rendering can place a larger burden on the server, which is why many modern web applications prefer frontend rendering. In that model, the server only provides the data the page needs, usually in JSON format, and JavaScript in the browser renders the page. We will talk about frontend rendering later. For now, we use the server-side rendering approach based on templates.

The steps for using a template page are shown below.

  1. Create a folder named templates in the project directory.

  2. Add the template page index.html.

    Note: In actual project development, static pages are provided by frontend developers. Backend developers need to modify the static pages into template pages, so that they can be rendered through Python programs. This is the server-side rendering mentioned above.

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Home</title>
            <style>
                #fruits {
                    font-size: 1.25em;
                }
            </style>
        </head>
        <body>
            <h1>Today's recommended fruits are:</h1>
            <hr>
            <ul id="fruits">
                {% for fruit in fruits %}
                <li>{{ fruit }}</li>
                {% endfor %}
            </ul>
        </body>
    </html>

    In the template page above, we used template placeholder syntax like {{ fruit }}, and we also used template instructions like {% for %}. These are all part of the Django Template Language, DTL. About template syntax and instructions, everyone can look at the official documentation. These contents are still easy to understand and do not need too much explanation.

  3. Modify the views.py file and call the render function to render the template page.

    from random import sample
    
    from django.shortcuts import render
    
    
    def show_index(request):
        fruits = [
            'Apple', 'Orange', 'Pitaya', 'Durian', 'Waxberry', 'Blueberry',
            'Grape', 'Peach', 'Pear', 'Banana', 'Watermelon', 'Mango'
        ]
        selected_fruits = sample(fruits, 3)
        return render(request, 'index.html', {'fruits': selected_fruits})

    The first parameter of the render function is the request object request, the second parameter is the name of the template page we want to render, and the third parameter is the data to be rendered on the page. We give the data to the template page through a dictionary. The keys in the dictionary are the variable names used in the template instructions or placeholders in the template page.

  4. Up to this point, render in the view function still cannot find the template file index.html. We need to modify the settings.py file and configure the path where the template file is located. Modify the settings.py file, find the TEMPLATES setting, and change the DIRS setting in it.

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates'), ],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
  5. Run the project again or directly refresh the page to view the result.

Summary

At this point, we have completed a very small web application with the Django framework. Although it does not have any practical value, through this project we can have a perceptual understanding of the Django framework. The best material for learning Django is definitely its official documentation. The official documentation supports multiple languages, and it also has tutorials for beginners to learn how to use the Django framework. It is recommended that everyone learn and use this framework by reading Django's official documentation. Of course, Django for Beginners style introductory books are also suitable entry-level reading for beginners.