The first experience of Django basic course

Time:2021-7-23

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 https://github.com/django/django.git
  • 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

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        wsgi.py

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 / settings.py: 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 / wsgi.py: the portal to the WSGI server of Django project

  • When entering the following command and entering the browser, enter:http://127.0.0.1:8000/ See Django started successfully

    $ python manage.py 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 manage.py is located, and enter the following command to create an application:

    $ python manage.py startapp demo

    The directory structure of the application is as follows

    demo/
        __init__.py
        admin.py
        apps.py
        migrations/
            __init__.py
        models.py
        tests.py
        views.py

    What these directories and files do:

    • Admin.py: manage admin background database model
    • Apps.py: 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
    • Models.py: write the model class file
    • Tests.py: files for testing
    • View.py: 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

    mysite/settings.py

Write the first view

Views are written in views.py of the application

demo/views.py

  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

/demo/urls.py

  from django.urls import path
  from . import views

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

Change the project URL and modify the routing by modifying the urls.py file of the project

/mysite/urls.py

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

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

Here, include forwards the demo / route to urls.py 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

database

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 / setting.py. 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

/mysite/settings.py

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 manage.py 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 manage.py createsuperuser

Next, start the project and type in the browserhttp://127.0.0.1:8000/admin 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 manage.py makemigrations to generate the migration file for the model changes.

  • Run Python manage.py migrate to apply the database migration.

Create a Book Model

Create a Book Model in demo application

/demo/models.py

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 manage.py makemigrations demo
Migrations for 'demo':
  demo\migrations
$ python manage.py makemigrations demo
Migrations for 'demo':
demo\migrations\0001_initial.py
- Create model Books
01_initial.py - 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 initila.py, you can use Python manage.py sqlmigrate demo 0001 to view the database migration operation and specific SQL statements

$ python manage.py sqlmigrate demo 0001
BEGIN;
--
-- 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);
COMMIT;

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 manage.py check
System check identified no issues (0 silenced).

Execute the migration command when there is no problem

$ python manage.py 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 manage.py 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

/demo/models.py

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 manage.py 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

/demo/admin

from django.contrib import admin

from .models import Books

admin.site.register(Books)

Rerun the project and enter in the address bar:http://127.0.0.1:8000/admin/ , 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

/demo/models.py

Register books in admin.py

Migrating databases

Add book data in Django background

Write a view showing books in the views.py of the application

/demo/views.py

from django.http import HttpResponse
from .models import Books


def book_list(request):
    book_list = Books.objects.all()
    books = {book.name : book.id 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

/tempaltes/index.html

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

/mysite/urls.py

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

from demo import views

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

Create a new urls.py file in the demo directory and add a route

/demo/urls.py

from django.urls import path

from . import views

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

Start the project, visit:127.0.0.1:8000/book/

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

/demo/urls.py

from django.urls import path

from . import views

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

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

/demo/views.py

def detail(request, id):
    book = Books.objects.filter(id=id).all()[0]
    content = {
        "name": book.name,
        "author": book.author,
        '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

/templates/detail.html

Start the project, visit:http://127.0.0.1:8000/book/ , 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.

/demo/views.py

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 […]