The first experience of Django basic course


Statement: the following is my personal understanding. If you find any mistakes or questions, you can contact me for discussion

brief introduction

After django2.0, Django does not support python2.7, so we need a system environment of python3. Here is an example of python3.6

Install Django

Installation in three ways

PIP installation

  • Generally, after installing python, it will help you to install pip. Use this when you don’t install itlinkInstall, remember to update to the latest version

  • Install and use virtualenv

  • Enter the following command in the created and activated virtual environment

    $ pip install Django

Through third party software package

Django for management system integration

Install development version

  • Install itgit

  • Enter the command to download Django

    $ git clone
  • Install and use virtualenv

  • Enter the following command in the created and activated virtual environment

    $ pip install -e django/

After installing Django, you can view the current Django version with the following command

$ python -m django --version

First experience of Django

Install and use virtualenv

See for detailed processThis link

Create Django project

Open the command line in the project directory and run the following command:

$ django-admin startproject mysite

After this sentence is executed, a Django project named MySite will be generated in the current directory. The directory structure is


What these directories and files do:

  • MySite / Directory: the container for storing items. Its name is not important and can be changed to any name you like

  • Manage. Py: the startup file of Django project. It allows you to manage Django project in various ways.

  • MySite / MySite / Directory: project directory, which stores project related files

  • MySite / MySite / configuration file for Django project

  • MySite / MySite / URLs. Py: the URL declaration file of Django project, which corresponds the URL to the view of the related app

  • MySite / MySite / the portal to the WSGI server of Django project

  • When entering the following command and entering the browser, enter: See Django started successfully

    $ python runserver

    The reason why Django can be successfully started here is that Django comes with a simple server (a lightweight web server written in pure Python). He can help us develop quickly.

Create an app

  • Switch the current directory to the directory where is located, and enter the following command to create an application:

    $ python startapp demo

    The directory structure of the application is as follows


    What these directories and files do:

    • manage admin background database model
    • related configuration of the app
    • Migrations / folder and its contents: the folder related to database migration, in which the migration version and migration information are stored
    • write the model class file
    • files for testing
    • write a view file

    We also need to register the app in the project configuration file, open the settings. Py file, and find installed_ Apps, add demoapp at the end of the list


Write the first view

Views are written in of the application


  from django.http import HttpResponse

  def index(request):
      return HttpResponse("Hello, world!")

In order to see the effect, we need to configure the URL, create a URLs. Py in the demo directory, and enter the code


  from django.urls import path
  from . import views

  urlpatterns = [

Change the project URL and modify the routing by modifying the file of the project


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

  urlpatterns = [
      path('demo/', include('demo.urls')),

Here, include forwards the demo / route to of the demo application. Whenever Django encounters an include, it truncates the part of the URL that matches this entry and sends the remaining string to the corresponding URLs. Py for further processing.

Path has five parameters: route, view, kwargs, name and pattern. Route and view are parameters that must be passed in

  • Route: criteria for matching URLs (similar to regular expressions). When Django responds to a request, he will start with the first item of urlpatterns and match it in order until he finds the matching item
  • View: target view function. When route finds a matching item, it will call the current view function and pass in an httprequest object as the first parameter. The parameter in route is passed in the form of keyword parameter
  • Kwargs: keyword parameter. Any keyword parameter can be passed to the target view function as a dictionary.
  • Name: the name of the URL. He can make Django quote him anywhere
  • Pattern: match pattern

Now you can start the Django program to see if it works properly


Create database

Enter MySQL and create a test database with the character set to utf8

$ mysql -uroot -p
mysql> create database test charset=utf8;
Query OK, 1 row affected (0.00 sec)

Database configuration

First of all, we need to configure the database options in MySite / Django defaults to SQLite database. If the personal project is not big, you can use this, or you can use your own familiar database. Django not only supports SQLite, PostgreSQL, mysql, or Oracle, but also supports many databases with third-party plug-ins. I use MySQL database


Database migration

Because Django’s own application has written some data models for us, even if we don’t write any models, we can directly use the database migration command to migrate

$ python migrate

You will see that many tables related to users and permissions are initialized

Create an administrator account, enter the user name, email address, password and confirm password in turn. It is recommended to set the password more complex

$ python createsuperuser

Next, start the project and type in the browserhttp:// Enter the background management interface

The first experience of Django basic course

Enter the account password and click login

The first experience of Django basic course

Database migration needs three steps

  • Write the models. Py file to change the model.

  • Run Python makemigrations to generate the migration file for the model changes.

  • Run Python migrate to apply the database migration.

Create a Book Model

Create a Book Model in demo application


The model has two fields, book title and author, which use character type and increase length limit(Note that Max must be added when using charfield_ Length limit

Create migration model and generate migration file

$ python makemigrations demo
Migrations for 'demo':
$ python makemigrations demo
Migrations for 'demo':
- Create model Books - Create model Books

The model books will be created, and there will be an additional 0001 in the migrations folder of the demo application_ For the migration file of, you can use Python sqlmigrate demo 0001 to view the database migration operation and specific SQL statements

$ python sqlmigrate demo 0001
-- Create model Books
CREATE TABLE `demo_books` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `book_name` varchar(200) NOT NULL, `auhtor` varchar(50) NOT NULL);

We need to pay attention to the following points:

  • The output content is related to the database used.
  • The default table name of the database is “application name”_ You can also customize the table name.
  • The primary key is automatically created by default, or you can customize it.
  • Django will customize relevant SQL statements for the database used, such as primary key: integer auto_ INCREMENT NOT NULL PRIMARY KEY,varchar:NOT NULL
  • The sqlmigrate command does not actually execute the migration command. It just outputs the process executed by the migration command to the screen for you to view

Execute the check command to check the project

$ python check
System check identified no issues (0 silenced).

Execute the migration command when there is no problem

$ python migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, demo, sessions
Running migrations:
  Applying demo.0001_initial... OK

Seeing the above, you have completed the database migration

Try it from the python command line

$ python shell

Here we see that the < queryset [< books: Books object (1) >] > does not let us know the details of this object. We can fix this problem by modifying the books model


After modification, re-enter the interactive terminal, and query again to display the title of the book. Here you can define the fields or contents you want to display

$ python shell

Add another book, aggregate function

>>> qbsz = Books(book_ Name: "the biography of Steve Jobs", author: "Walter Isaacson"

Next, we add the books model to the admin management, and give the books to the admin management through the register method


from django.contrib import admin

from .models import Books

Rerun the project and enter in the address bar: , enter the account and password to log in and view the model

The first experience of Django basic course

Click in to view the data of the model, add in the upper right corner, delete actions, and click the book name to see more details

The first experience of Django basic course

Views and templates

Add a Book model to models. PY


Register books in

Migrating databases

Add book data in Django background

Write a view showing books in the of the application


from django.http import HttpResponse
from .models import Books

def book_list(request):
    book_list = Books.objects.all()
    books = { : for book in book_list}
    return render(request, 'index.html', context={'books': books})

Rendering by template

Create a new index. HTML file in the templates directory


Add a Book route to the URLs. Py file of the project


from django.contrib import admin
from django.urls import path

from demo import views

urlpatterns = [
    path('book/', include('demo.urls')),

Create a new file in the demo directory and add a route


from django.urls import path

from . import views

urlpatterns = [
    path('', views.book_list, name='index'),

Start the project, visit:

The book list page is complete, and then write the book details page

Add a route to the details page in the URLs. Py file in the demo project


from django.urls import path

from . import views

urlpatterns = [
    path('', views.book_list, name='index'),
    path('<int:id>/', views.detail, name='detail'),

In the file of demo project, write the view function of detail page


def detail(request, id):
    book = Books.objects.filter(id=id).all()[0]
    content = {
        'publish_house': book.publish_house,
        'publish_date': book.publish_date,
        'price': book.price,
        'synopsis': book.synopsis
    return render(request, 'detail.html', context=content)

Create a new detail. HTML file in the Templates folder and write the code


Start the project, visit: , click one of the books to see the details page, or directly select an ID to access the details page. At this time, there will be a problem. When accessing a nonexistent ID, there will be an error. We need to customize the error page and modify the detail view function.


Here is the 404 error page of Django, we need to return the error description

This work adoptsCC agreementReprint must indicate the author and the link of this article

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]