preface

Django is an open source Web framework written in Python that allows you to quickly build high-performance Web sites.

Before you can read this article, you need to have some basic knowledge of The Python language. I started learning Django after getting started with Python. While Python may be similar to the syntax of the language you are currently using, all languages have similar syntax. If you are good at one language, you can easily read other languages. However, if you can read it, you may not be able to write it.

I’ve never had any experience with Python before, so this article is a good fit for mobile developers like me, learning Django from scratch, because we all embrace Web frameworks from a mobile point of view, and it probably resonates more.

In fact, if you want to really do Web development, you still need to be familiar with front-end HTML, CSS, JavaScript and other languages, as well as database operations, etc. The technology stack is relatively extensive, and we will gradually accumulate and learn later. This article focuses on learning how to use Django.

By the end of this article, you should at least be comfortable with using Django to interface to the front end, manipulate databases, and so on.

Setting up the development environment

My own development environment is as follows:

  • MacOS Catalina 10.15.7,

  • Python 3.7.3,

  • Django 3.1.2,

    In order to follow the following operations more smoothly, try to keep your version and mine consistent, can avoid some of the differences between versions.

Install python

$ brew install python3
Copy the code

After the installation is complete, use python -v to verify that the installation is complete, and print the correct version number.

Virtualenv

It is recommended to use Virtualenv for Django development. Virtualenv is a Python tool that allows you to create a standalone Python environment. For example, create a virtual environment where you can learn Django, completely isolated from the previous environment on your computer.

Install using Virtualenv

Install Virtualenv

$ pip3 install virtualenv 
Copy the code

Specify a directory to create a virtual environment

$virtualenv abc-env Specifies the name of the virtual environmentCopy the code

Enter the Virtual Environment

$ source /Users/xxx/abc-env/bin/activate 
Copy the code

Exiting a Virtual Environment

$ deactivate
Copy the code

Simplify the operation of virtual environments (you can skip the previous steps and install virtualenvWrapper directly, which will automatically download and install virtualEnv)

$ pip3 install virtualenvwrapper
Copy the code

Create a folder to store the virtual environment

$ mkdir ~/.virtualenvs
$ cd ~/.virtualenvs
Copy the code

Check the paths of python3 and VirtualenvWrapper. sh and save them

$ which python3
$ which virtualenvwrapper.sh
Copy the code

Configuring environment Variables

$ vim ~/.bash_profileAdd the following code using the path saved above: Export WORKON_HOME='~/. Virtualenvs' // The created virtual environment is saved in this directory. Export VIRTUALENVWRAPPER_PYTHON='Python3 path 'source Virtualenvwrapper. Sh pathCopy the code

Save environment variables

$ source ~/.bash_profile
Copy the code

Creating a Virtual Environment

$ cd ~/.virtualenvs
$Mkvirtualenv my_env will automatically enter the virtual environment
Copy the code

View which virtual environments are installed

$ lsvirtualenv
Copy the code

Install Django

Install in a virtual environment

PIP install django = = 3.1.2Copy the code

The version number is specified here; if not, the latest version will be installed.

Creating a Django project

Django Project is the code container for the entire project, including our own Python code and all the configuration files and code Django automatically generates. The following is a simple example of how to create a charm by command. You can also create a charm by pyCharm.

Create a Django project command line method (into a Django virtual environment)

$Django-admin startProject first_project //first_project is the project name
$ cd first_project
Copy the code

Run the project

Django provides a Web server for local development. To start a Web server locally, run the python manage.py runserver command from the command line:

$ python manage.py runserver
Copy the code

Enter http://127.0.0.1:8000/ in the browser to see the page, prompting It worked!

Changing the port number

$ python manage.py runserver 9000
Copy the code

Stop running

$ control + c
Copy the code

Access with other computers on the LAN

Python manage.py runserver 0.0.0.0:8000 2 In the setting.py file, configure ALLOWED_HOSTS to add the local IP address, such as ALLOWED_HOSTS = [‘10.100.4.10’]

Look at the manage.py subcommand

$ python manage.py help
Copy the code

Now that you’re all set, get started with Django.

The project practice

The first Django application

You’ve already created the project and run the page, which Django generates by default. Now it’s time to start writing our own business code.

Our own code is recommended to be written to different applications according to business requirements, so that the future engineering structure is clear and easy to maintain.

Go into the virtual environment and create an application, which is one level smaller than the “project” above. A project can contain multiple applications. Depending on business requirements, you can create multiple “applications” for the “project” that are responsible for different functions.

python manage.py startapp blog
Copy the code

If you refresh the directory, you’ll see that there’s a new blog folder, and you’ve already created it and you need to set it in settings.py in the project directory,

Find the INSTALLED_APPS setting and add blog to it

INSTALLED_APPS = [
    'django.contrib.admin'.'django.contrib.auth'.'django.contrib.contenttypes'.'django.contrib.sessions'.'django.contrib.messages'.'django.contrib.staticfiles'.'blog'
]
Copy the code

Request and Response

The interaction process of a Web application is the process of HTTP request and response. It can be simply understood as the process of the browser opening a URL and returning the response data.

Django has a well-established mechanism for handling HTTP requests and responses, and it only takes two steps to develop an external interface.

  1. The view function

Write view functions in views.py:

from django.http import HttpResponse
# Create your views here.

def index(request) :
    return HttpResponse("My first interface.")
Copy the code

This view function represents how the Web server receives an HTTP request from the user, processes it based on the request content, and returns the result as an HTTP response to the user. It first accepts an argument called Request, which is an HTTP request Django has wrapped for us, an instance of the Httprequest-like HttpRequest. We then return an HTTP response directly to the user. This HTTP response is an instance of the HttpResponse class that Django wrapped for us, but we pass it a custom string argument.

  1. Bind URL and view functions

By binding the URL to the view function, the HTTP request initiated by the user can be accurately located in the response function.

urlpatterns = [
    path(' ', views.index),
]
Copy the code

Here to introduce a more important knowledge point, URL naming.

The url naming

Because urls change a lot, if you write dead urls in your code you have to change your code a lot, so you name the URL, and when you use the URL, you reverse the name, you don’t need to use dead urls. To do this, add a name parameter to path:

Path ('signin/', views.login, name='login'),Copy the code

Application namespace

To prevent multiple apps from having urls with the same name and avoid confusion when reversing urls, you can use the App namespace to make the distinction by defining an app_name variable in your App’s urls.py

App_name = 'front' urlpatterns = [path('', views.index), path('login/', views.login), Path ('signin/', views.login, name='login'),]Copy the code

Inversion of URL:

login_url = reverse('front:login')
Copy the code

Routing classification

Finally, import urls in each App through include in urls.py of the project. Attention should be paid to the stitching of URLS. The final URL requested by the business is the outer path+ the inner path, for example:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path(' ', include('front.urls')),
    path('sales/', include('sales.urls')))# the inner path
urlpatterns = [
    path('orders/', views.listorders)] the final business request URL is Sales/Orders /Copy the code

The database

Database knowledge, normally speaking, is not the content that this article should focus on, but it is something that has to be said. Without data, there is no way to continue to do projects in the future, so we still have to put the content of the database in the front of the comparison. Also make a data basis for the following study.

There are a lot of practical Django practice projects on the Internet. I learned several practical projects by myself, such as library management system, campus management system, etc., through the “B website” and the blogs of the big guys, before starting the internal projects of the company. I feel that I must go through such a process so that I can serve the company with self-taught knowledge

In a future article, we’ll use a hands-on project as an example to share some of the apis and techniques we need to master with Django, and post key code. Let’s take a look at the ORM system Django provides and see how it can help developers simplify their database development.

The ORM is introduced

As we know, in the daily database development, THE SQL statement is very repeatable, the utilization rate is very low, and there are hidden dangers of SQL injection. There is no need to write native SQL statements. A model corresponds to a table, and properties correspond to fields in the table. Operation objects can automatically execute database statements.

In Django

  • To define a database table, you define a class that inherits from Django.db.models.Model
  • To define the fields (columns) in this table, you define the attributes of the class
  • Class methods are methods for processing data in the table, including adding, deleting, modifying, and searching data

This greatly simplifies the database development in our application, without the use of SQL statements to improve the development efficiency; Second, the low-level details of accessing different databases are shielded, and if you need to change databases, you hardly need to change the code, just a few configuration items can do it.

The ORM to use

Create the model

Define the table in models.py in the application blog created above:

from django.db import models
from django.contrib.auth.models import User
# Create your models here.

class Category(models.Model) :
    "" "Django's built-in type to view all documents: https://docs.djangoproject.com/en/1.10/ref/models/fields/#field-types "" "
    name = models.CharField(max_length=100)


class Tag(models.Model) :
    name = models.CharField(max_length=100)


class Post(models.Model) :
    title = models.CharField(max_length=70)
    CharField can be used to store short strings, but the body of the article might be a large chunk of text, so use TextField to store large chunks of text.
    body = models.TimeField()
    created_time = models.DateTimeField()
    modified_time = models.DateTimeField()
    # blank=True Allows null
    excerpt = models.CharField(max_length=200, blank=True)
    # This is classification and tag, the model of classification and tag we have defined above.
    # Here we associate the database table corresponding to articles with the database table corresponding to categories and tags, but the association form is slightly different.
    # we stipulate that an article can only correspond to one category, but there can be multiple articles under one category, so we use ForeignKey, that is, one-to-many association relationship.
    # For tags, an article can have multiple tags, and there may also be multiple articles under the same tag, so we use ManyToManyField to indicate that this is a many-to-many association.
    We also specify that articles can have no tags, so we specify blank=True for tags.
    # If you are not familiar with ForeignKey and ManyToManyField, please see the explanation in the tutorial, or refer to the official documentation:
    # https://docs.djangoproject.com/en/1.10/topics/db/models/#relationships

    # on_delete specifies the behavior of the system when deleting primary key records pointed to by foreign keys
    # CASCADE Delete all database records that are dependent on each primary key
    # PROTECT delete if found to be associated
    Blank =True, null=True
    category = models.ForeignKey(Category, on_delete=models.PROTECT)
    tags = models.ManyToManyField(Tag, blank=True)
    # the authors, this User is from the django. Contrib. Auth. Models of import.
    Contrib. Auth is a built-in django application designed to manage web User registration, login, etc. User is a User model django has written for us.
    # here we associate the article with the User via ForeignKey.
    # Since we stipulate that an article can only have one author, and an author may write multiple articles, this is a one-to-many association, similar to a Category.
    author = models.ForeignKey(User, on_delete=models.PROTECT)
Copy the code

Here CharField corresponds to the vARCHAR type in the database, and there are other types, you can learn by yourself, and the type in the database one by one correspondence.

Note:

  • Table names are automatically generated by Django. The default format isProject name + underscore + lowercase class name“You can rewrite the rule.
  • Django automatically creates auto-increment primary keysidOf course, you can specify the primary key yourself.
  • The SQL statement above is based onPostgreSQLSyntax.

To generate table

Once the model is created, you need to register the app that models.py belongs to in your Settings file.

The following two commands will check the blog module to see if there are any models-related changes.

1. Hoisting Generates migration script files

$Python Manage.py Makemigrations Automatically detects which models have been modified and automatically generates scripts
Copy the code

2. Mapping to the database, the first time, will map to other tables in Django’s default install_apps

$ python manage.py migrate
Copy the code

If the created model needs to be modified, add fields, etc., the preceding two commands need to be executed again, and each change generates a new Python file in the Migrations folder that records each change

You can also run the following command to see what Django does for us after executing the above two commands:

python manage.py sqlmigrate blog 0001
Copy the code

Sqlite3 is built into Python’s built-in SQlite3 database. Sqlite3 is a lightweight database that has only one file. The database-related configuration is in settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3'.'NAME': BASE_DIR / 'db.sqlite3',}}Copy the code

Of course, you can also use the MySQL database, which we’ll talk about later. For a brief, small project, SQlite3 will suffice.

Model is introduced

In creating the model above, you can use many fields, define different types of properties, and define methods for the model, as described below.

field

Each Field in the model is an instance of the Field class, and the Field determines the data type of the modified column in the database table.

Common field types
  1. BooleanField Boolean value type. Default: None.
  2. The CharField string type is the most commonly used type, and max_length is a mandatory parameter representing the length of the string.
  3. DateField Date type
  4. DateTimeField Date-time type, with more hours and seconds than DateField
  5. EmailField email type. You can use Django’s built-in email validation.
  6. FileField Indicates the type of the uploaded file
  7. IntegerField Specifies the integer type, which is the most commonly used type
  8. TextField Text type, used to store a large amount of text content.

Methods and Properties

The methods of the model are the instance methods of python classes. For repeated operations on a single piece of database data, we can add custom methods to the model.

In addition to defining methods, you can also define attributes for the model, which are different from the above, where each attribute is a column in a database table. The attributes here are not listed as a column in a table, but as a property of this Python class.

Here is a sample code for your reference to understand the definition of model methods and attributes:

class Category(models.Model) :
   
    name = models.CharField(max_length=100)

    # is a popular category
    The instance is called as a function
    def name_is_hot(self) :
        if self.name == 'hot':
            return True
        else:
            return False

    The instance is called as an attribute
    @property
    def full_name(self) :
        "Return the category full name"
        return '%s %s' % ('full', self.name)

    def __str__(self) :
        return self.name + self.full_name
Copy the code

Relational type field

Django also defines a set of relational-type fields that represent models and relationships between models.

More than a pair of

A common foreign key is a one-to-many relationship. The following illustrates a one-to-many table relationship using tables for customers, drugs, and orders.

class Customer(models.Model) :
    # Client name
    name = models.CharField(max_length=200)

    # Contact number
    phonenumber = models.CharField(max_length=200)

    # address
    address = models.CharField(max_length=200)

    # QQ can be an empty string
    qq = models.CharField(max_length=100, null=True, blank=True)


# drug
class Medicine(models.Model) :
    name = models.CharField(max_length=200)
    sn = models.CharField(max_length=200)
    desc = models.CharField(max_length=200)
Copy the code

In order, a customer can have multiple orders, customers do the foreign key in the order table. If a field in a table is a foreign key, the value of the foreign key field can only be the value of a record in the primary key of the associated table.

In the two tables defined above, you will see that there are no primary keys defined. When you execute Migrate, Django will generate an ID field for the database table that corresponds to the Model.

After you design the Order table migrate you will see that the Customer table is associated with the foreign key customer_id in the database

class Order(models.Model) :
    name = models.CharField(max_length=200, null=True, blank=True)

    create_date = models.DateField(default=datetime.datetime.now)
    # foreign key on_delete Specifies the behavior of the system when deleting primary key records pointed to by foreign keys
    # CASCADE Delete all database records that are dependent on each primary key
    # PROTECT delete if found to be associated
    Blank =True, null=True
    customer = models.ForeignKey(Customer, on_delete=models.PROTECT)
Copy the code
One to one

One-to-one relationships are easier to understand. For example, Django generates the default user table auth_user. When we need to extend the user information for business purposes, we can either extend the fields in the auth_user table or create a new table that depends on the auth_user table, such as the sales table. Each salesman is an auth_user, so the relationship between the two tables is one-to-one, and the other information related to the salesman can only be stored in the sales table, without modifying the original structure of the auth_user table.

The one-to-one structure is essentially a foreign key. Django uses OneToOneField to represent the one-to-one foreign key relationship.

Many to many

In addition to the two above, there are many-to-many relationships. In the example above, the relationship between the order and the drug is many-to-many.

class Order(models.Model) :
    name = models.CharField(max_length=200, null=True, blank=True)

    create_date = models.DateField(default=datetime.datetime.now)
    # foreign key on_delete Specifies the behavior of the system when deleting primary key records pointed to by foreign keys
    # CASCADE Delete all database records that are dependent on each primary key
    # PROTECT delete if found to be associated
    # SET_NULL After deletion, the associated local value is set to null
    customer = models.ForeignKey(Customer, on_delete=models.PROTECT)
    # Many-to-many relationships
    medicines = models.ManyToManyField(Medicine, through='OrderMedicine')


class OrderMedicine(models.Model) :
    order = models.ForeignKey(Order, on_delete=models.PROTECT)
    medicine = models.ForeignKey(Medicine, on_delete=models.PROTECT)
    # Quantity of drugs in order
    amount = models.PositiveIntegerField()
Copy the code

The many-to-many relationship in Django is actually implemented through another table, the one specified by the through parameter. If the through parameter is not specified, the system also generates a custom table to manage many-to-many relationships. Here we specify a table OrderMedicine to implement, and new fields can be added for business use.

Field parameters

All fields in the model can accept some parameters, some of which are specific to a particular field type. The following are the parameters that can be set for all fields.

  • Null Holds null values in a database
  • The blank field is allowed to be null
  • Choices are like enumerations
  • The default value of the default field
  • Primary_key Primary key, automatically generated or configurable

Metadata Meta

The metadata of the model is the content in addition to the defined fields, such as sorting methods, database table names, and so on.

class Tag(models.Model) :
    name = models.CharField(max_length=100)
		created_time = models.DateTimeField()
     class Meta:
        ordering = ['-created_time']
Copy the code
  • One of the most common metadata ordering, specify the model to generate all objects of the sort of way, if in front of the field name plus character “-” indicates descending order, if you use character question mark “?” Random permutation.

  • Db_table Specifies the name of the table that this model will generate in the database

Operating database

Frequently asked Questions collection

In the operation of the database is possible to encounter problems, are recorded here, will continue to update ~

  1. The correct Django Django. Core. Exceptions. ImproperlyConfigured: Error loading MySQLdb module

NameError: name ‘_mysql’ is not defined

Pymysql PIP install pymysql PIP install pymysql pymysql PIP install pymysql

import pymysql
pymysql.install_as_MySQLdb()
Copy the code

** mysql_config not found **

The solution

Perform:

ln -s /usr/local/mysql/bin/mysql_config /usr/local/bin/mysql_config
Copy the code

The reason:

Mysql_config cannot be found because mysql_config is located in /usr/local/mysql.bin/and is not accessible anywhere

Link mysql_config to the /usr/local/bin directory

  1. Error: Forbidden (403) CSRF verification failed. Request aborted

You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.

If you have configured your browser to disable cookies, please re-enable them, at least for this site, Or for the “same origin” requests.

Solution:

By default, Django enables a CSRF security mechanism to prevent forgery of cross-site requests. This means that all POST and PUT requests must contain validation data in the HTTP request header. We learned here that to keep things simple, we should disable CSRF validation. Settings in the configuration file. The MIDDLEWARE in py configuration items commented in django. MIDDLEWARE. CSRF. CsrfViewMiddleware can.

Reading database data

Continuing with the Customer table we created earlier, we implement a function: the browser calls sales/ Customers /, and our server returns all Customer records in the system to the browser.

First, we implement a function that handles sales/ Customers/access requests and returns all records of table Customer in the database.

def listcustomers(request) :
    Return a QuerySet object containing all table records
    Each record is a dict object
    qs = Customer.objects.values()

    retStr = ' '
    for customer in qs:
        for name,value in customer.items():
            retStr += f'{name}:{value}| '
        retStr += '<br>'
    return HttpResponse(retStr)
Copy the code

To further update the requirements, how do I get a parameter in the URL? http://127.0.0.1:8000/sales/customers/?phonenumber=18970992909

def listcustomers(request) :
    Return a QuerySet object containing all table records
    Each record is a dict object
    qs = Customer.objects.values()

    Check if there are parameters in the URL
    ph = request.GET.get('phonenumber'.None)

    if ph:
        qs = qs.filter(phonenumber=ph)

    retStr = ' '
    for customer in qs:
        for name,value in customer.items():
            retStr += f'{name}:{value}| '
        retStr += '<br>'
    return HttpResponse(retStr)
Copy the code

The session mechanism:

The server stores a session table in the database to record information about a user login. Each time a user logs in and invokes login, a session data will be generated in and out of the session table. In addition, sessionID data, which is the session key field in the session table, will be entered in the set-cookie message header of the successful login response.

Set-Cookie:sessionid=eruio3789r09fjoiuro2
Copy the code

After receiving the response, the client will store the sessionID in the cookie of the client, depending on the location of the client’s browser, which is the job of the browser. Subsequent access to the server must include this cookie data in the HTTP request message.

Cookie:sessionid=eruio3789r09fjoiuro2
Copy the code

After receiving the request, the server only needs to check whether there is a record corresponding to the sessionID in the session table to determine whether the request is sent by the user who has logged in previously. If not, the server can deny the service and redirect the HTTP request to the login page.

Token:

Session support, which Django supports by default.

ORM operations on associated tables

Reverse query

We have obtained a Country object, access all students belonging to this Country, and obtain all reverse foreign key association objects by converting the table model name to lowercase followed by _set.

cn = Country.objects.get(name='China')
cn.student_set.all(a)Copy the code

You can also define the model with the related_NAME parameter for the foreign key field

class Student(models.Model) :
    name = models.CharField(max_length=100)
    grade = models.PositiveSmallIntegerField()
    country = models.ForeignKey(Country, on_delete=models.PROTECT, related_name='students')
Copy the code

Can be more intuitive to reverse the query

cn = Country.objects.get(name='China')
cn.students.all(a)Copy the code

Inverse filtering

Find the country of the student in grade 1, using distinct de-weight

Country.objects.filter(students__grade=1).values().distinct()
Copy the code

Associative table insert

Continue to use the Order table described above to process the request to add the Order. Here we add an Order data and need to add records in two tables (Order, OrderMedicine). Both types of table inserts require two database operations. Above, we have always assumed that the database insert operation is successful, but in practice, we will definitely encounter insert failure.

For an order data here, the operation of inserting two times into the database may lead to the success of one insert and the failure of the second one, resulting in dirty data. Those of you who know about databases will know that we should use the transaction mechanism of databases to solve this problem.

Put a batch of database operations into a transaction, and if any of the database operations in the transaction fail, the entire transaction is rolled back, undoing the previous operations, and the database is rolled back to the state before the transaction.

Now lets see how Django implements transactions. The transaction mechanism is implemented using the transaction.atomic() atomic operation.

from django.db import transaction

def addorder(request) :
    info = request.params['data']

    with transaction.atomic():
        new_order = Order.objects.create(
            name=info['name'],
            customer_id=info['customer_id']
        )
        batch = [OrderMedicine(order_id=new_order.id, medicine_id=mid, amount=1)
                 for mid in info['medicineids']]
        OrderMedicine.objects.bulk_create(batch)  # bulk_create Creates multiple data
    return JsonResponse({'ret': 0.'id': new_order.id})
Copy the code

Query operation

  1. Exact: at the bottom will be translated as’ = ‘
  2. Iexact: at the bottom will be translated as’ LIKE ‘
    • The difference between exact and iexact is the difference between like and =
  3. Queryset. query is used to query the SQL statement that the ORM statement has been translated into. It cannot be used in ordinary ORM models. For example, it cannot be used to obtain data from GET. 5. Icontains: is case insensitive to the search for a string that appears in the specified field LIKE %hello world%. At the MySQL level, like is case-insensitive. 6. Contains and icontains are translated into SQL using “% %”.

Common problem: ‘django. Core. Exceptions. ImproperlyConfigured: mysqlclient 1.4.0 or newer is required; You have 0.9.3.’ import pymysql pymysql.version_info = (1, 4, 13, “final”, 0) pymysql.install_as_MySQLdb()

Aggregation function

Avg: Calculate the average value

Aggregate functions cannot be run alone. They need to be run under methods that can execute aggregate functions, such as aggregate. When the aggregate function is finished, the value of the aggregate function is named field__+ the aggregate function name. Sample code is as follows

result = Book.objects.aggregate(price_avg=Avg("price")) # price_avg alias
Copy the code

Aggregate returns a dictionary, and key is the custom name, or the default name of the aggregate function, and the value is the value that the aggregate function gets

QuerySet API

Model objects.

This object is django. Db. Models. The manager. The manager of the object, this class is an abstract class, he copy all the methods above are from the QuerySet.

QuerySet common methods

filter

filter

exclude

Exclude satisfy condition

annotate

Renames the value of the field obtained

Student.objects.annotate(
    countryname='country__name',
    studentname='name'
).filter(grade=1, country__name='China').values('studentname'.'countryname')
Copy the code
order_by

Sort the query results by a field

values

The form

Creating a Super Administrator

python manage.py createsuperuser
Copy the code

Create administrator, according to the prompt input password, email, password, etc., create a successful view of the user table in the database, you can see the data of the user created just now.

The browser to open the http://127.0.0.1:8000/admin/, you can see the Django’s built-in login page, input username and password you just created users can login successfully. After login, you can add new users and other operations in the background.

At this point you may be wondering why the table Customer that we created ourselves is not displayed in the background. How to operate the Customer table in the background? It’s as simple as modifying the configuration file common/admin.py and registering the Customer class we defined

from django.contrib import admin
from .models import Customer

admin.site.register(Customer)
Copy the code

Refresh the http://127.0.0.1:8000/admin/, you can see operation ` Customer ` table entry. Add a piece of data and check whether the database has been successfully added.

Django template

Understand the process of the HTTP request, we can take a slightly more advanced again, for mobile terminal, is already enough, only need the response data, but for the browser, may also want to show a good page, Django also did a lot of work in this aspect, can let developers use simple code, showing a page quickly. Thats djangos templating system.

Create an index.html file in the templates folder at the root of your project, and change ‘DIRS’: [] to ‘DIRS’ in your project settings.py: [os.path.join(BASE_DIR, ‘templates’)],

Apply colours to a drawing template

Django provides two ways to render a template, render_to_string and render:

from django.shortcuts import render
from django.template.loader import render_to_string

def index2(request) :
    html = render_to_string("index.html")
    return HttpResponse(html)

def index3(request) :
    return render(request, 'index.html')
Copy the code

Pages are definitely not static pages, so you can also pass parameters to the template through context at render time

from django.shortcuts import render

def index(request) :
    return render(request, 'index.html', context={
        'title': 'My Blog'.'welcome': 'Welcome to my blog'
    })
Copy the code

So how do you get this entry in an HTML template? This is the template variable we’ll talk about next.

Template variables

1. To use variables in a template, place them in {{variables}}

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ title }}</title>
</head>
<body>
    <h1>{{ welcome }}</h1>
</body>
</html>
Copy the code

2. Access variable properties through the object. Property name, the test code is as follows:

class Person(object) :
    def __init__(self, username) :
        self.username = username
        
def prjectIndex(request) :
    p = Person('zhangsan')
    context = {
        'username': "xiaoming".'person': p,
        'personDic': {
            'username': 'hhh'

        },
        'persons': [
            'aaaa'.'bbbbb']}return render(request, 'index.html', context=context)
Copy the code

The HTML template can be obtained as follows:

<h1>{{ person.username }}</h1>
Copy the code

3. Dictionary type variables, which can be accessed through dictionary. Key.

<h1>{{ personDic.username }}</h1>
Copy the code

4. Lists or tuples also pass. Access. The HTML template can be obtained as follows:

<h1>{{ persons.0 }}</h1>
Copy the code

If the label

In addition to fetching variables from view functions, you can also write some logical code in templates. Django also provides some logical tags for us.

The if tag corresponds to the if statement in Python, elif and else if, and all tags need to be wrapped in {% %}. The if tag can be used with ==,! =, <=, >=, >, <, in, not in, is,is not

   {% if age < 18  %}
        <p>A minor</p>
    {% elif age == 18 %}
        <p>18</p>
    {% else %}
        <p>adult</p>{% endif %} {% if 'ruban' in heros %}<p>Ruban in</p>
    {% else %}
        <p>Ruban not</p>
    {% endif %}
Copy the code

For the label

<! Use keys to traverse dictionary for tag -->
    <ul>
        {% for key in person.keys %}
        <li>{{ key }}</li>
        {% endfor %}
    </ul>
Copy the code

for… in… The label

for… in… Note that there are no continue and break tags

! -- for tag traverses dictionary values --><ul>
        {% for value in person.values %}
        <li>{{ value }}</li>
        {% endfor %}
    </ul>

<! -- for tag is used to traverse dictionary key-value pairs -->
    <ul>
        {% for key,value in person.items %}
        <li>{{ key }}/{{ value }}</li>
        {% endfor %}
    </ul>
Copy the code

The filter

Function calls () are not supported in DTL. There is no support for passing parameters to functions. A filter is actually a function and can accept parameters (up to two parameters)

add

Numeric direct addition list merges string concatenation

    {{ "1"|add:"2" }}
    {{ value1|add:value2 }}
Copy the code

Cut Cuts the target string

    {{ "hello world"|cut:" " }}
Copy the code

Date Date formatting

{{today | date: "Y/m/d"}} {{today | date: "d - m - Y"}} {# n in front not 0 # 1-9} {{today | date: d - n - "Y"}} {j day # 1-9 is 0 #} {{ today|date:"j-n-Y" }} {{ today|date:"Y/m/d g" }} {{ today|date:"Y/m/d H:i" }}Copy the code

Template inheritance

Must be the first line in the child template (can be preceded by a comment line)

    {% extends 'base.html' %}
Copy the code

Only code in block tags can be loaded

{% block content %} {{block.super}} this is the home page {% endblock %} block outside the code is not loaded and not renderedCopy the code

Variables defined in child templates can be read from parent templates