Diango: Django basics

One, create a python virtual machine and install Django

To solve the dependency problem of different versions of the same package, use the python virtual machine. Installing the package in the virtual machine does not affect the package in the actual environment.

The virtual machine actually replicates the python environment on the physical machine.

Create virtual environment command:

mkvirtualenv <虚拟环境名>

Such as creating a python3 virtual environment:

mkvirtualenv -p python3 bj11_py3

Enter the virtual environment to work:

workon <虚拟环境名>

Check how many virtual environments are on the machine:

workon 空格 + 两个tab键

Exit the virtual environment:

deactivate

Delete the virtual environment:

rmvirtualenv <虚拟环境名>

The command to install the package in a virtual environment:

pip install 包名

Note: sudo pip install package name cannot be used. This command will install the package on the real host environment instead of the virtual environment.

Check which python packages are installed in the virtual environment:

pip list

pip freeze

Install django environment:

pip install django==1.8.2

The steps to build a django project are as follows:

1. Create a django project

2. Create an application

3. After creating the application, you need to register the application. That is, add the corresponding code in setting.py

Add a line of app names at the end of INSTALLED_APPS.

4. Run python manage.py runserver

Two, Django project structure

Django follows the MVT architecture

M: Model and database interaction

V: The view accepts the request and processes it

T: Template generates HTML page

Create django project

File description

__init__.py : indicates that this is a python package

settings.py : project configuration file

url.py : url routing

wsgi.py : wsgi protocol, the entry point for web server and django interaction

manage.py : project management file, through which the entire project is managed

Create application

 

 

File description

admin.py : To establish the connection between the application and the project, the application needs to be registered. Website management related documents

models.py : Interaction module with database

views.py : define processing functions, view functions, and return responses

tests.py : A file for writing test code

Database configuration

 

Three, create a model

1. Write the model class in the modles.py of the application and inherit the models.Model class

class Book(models.Model):
    name = models.CharField(max_length=20)  #定义字符串格式,设置最大值
    data = models.DateField #定义时间格式
    number = models.IntegerField    #定义整数格式

Specify which table in the database to use. You can override the Meta class in the model class. This class is used to specify the table name:

class Meta:
db_table = '表名'

2. After creating the model class, execute the command to generate the migration file

python manage.py makemigrations

After the execution is successful, there will be an additional migrations package under the app package

3. Perform the migration to generate the table

python manege.py migrate

 

4. Set the table administrator under adim.py

admin.site.register(User_Info)

or

admin.site.register(User_Info,UserAdmin)	第二个参数表示由哪个用户管理,默认admin

4. Operate data tables and model database relationships through model classes (model)

Use model classes to CRUD data tables

1. Import the models module into the models in the app

from django.db import models

2. Create an instance with a module class

b = Book()

3. Assign values ​​to the attributes of the instance

b.name = "a book"

b.number = 23

4. Call the save attribute of the instance and write the content to the database

b.save()

5. Query

The get method of the objects class in the module class can query the qualified instance and return the instance.

b2 = Book.objects.get(id=1)

type(b2)

Returns: AppTest.models.Book

You can view the properties of b2, such as:

h1.book.name

返回: a book

After modifying the properties, call the save function to update the database

6. Delete

b.delete()

Model relationship

1. When creating multiple categories, add foreign keys to multiple categories, and the foreign key value is the class name (table name) of one category, such as:

class Hero():

name = models.CharField(max_length=20)

age = models.IntegerField()

#添加外键(django 2.0以上,需要加上on_delete,否则会报错)

book = models.ForeignKey("Book", on_delete=models.CASCADE)

2. Create an instance

Multi-class creation instance is basically similar to one-class, the things to note are:

The parameter of the foreign key in Duo Tiong is an object. That is, an instance of a class.

3. View the associated table properties

Multi-class : After creating a multi-class instance, the foreign key attribute of the instance is an object, which is an instance of one class. Therefore, that object can be used to obtain the properties of a class of instances.

One category : To view all related multiple categories in one category, use: instance.multi-class name_set.all(), or multiple-class name_set.get().

Note : The class name is lowercase by default

Five, background management (model)

1. Localization (language, time)

Modify the setting.py file under the project

2. Create an administrator

command:

python manage.py createsuperuser

After the creation is successful, enter the background management interface at IP:PORT/admin

3. Register the model class

Register the model class in admin.py under the application.

Tell the djang framework to generate the corresponding table management page according to the registered model class.

4. Customize the management interface

The default display of the management interface:

 

If you need to make the name display custom content, rewrite the __str__ function in the model class. What the function returns will be displayed here. Such as:

5. Customize the management interface

Need to write a custom management model class in admin.py. The class name can be customized, such as

class BookAdmin(admin.ModelAdmin):

list_display=['name','number']

Note: The fields written in list_display are the fields displayed on the interface.

When registering the model class in admin.py, specify the management model class in the parameter, such as:

admin.site.register(Book, BookAdmin)

Note: The first parameter in brackets is the model class, and the second parameter is the management model class.

6. View configuration and redirection

1 Configure urls.py in the application

Add urls.py under the application to the list of urlpatterns in urls.py under the project

导包:from django.conf.urls import include,url

语法:path('', include("AppTest.urls")), 或

url(r'^', include("AppTest.urls")),

There are two parameters in the path, the first is the first character after the IP when accessed, such as admin. The second parameter is urls.py under the application with the include function.

2. Configure urls.py under the application

Write the route in the urlpatterns list in urls.py under the application, such as:

语法:url(r'^index', views.index)

There are two parameters in url, the first parameter is the page visited by the browser, and the second parameter is the function in view.py.

3. Define the view function to return the browser request

Add the view function in the views.py of the app, the parameter is HttpRequest. Need to return HttpResponse()

from django.http import HttpResponse

def index(request):

return HttpResponse(.......)

Note: Page jump, if you visit a page and you want to return the content of another page, write it like this when you return:

return HttpResponseRedirect('/index')

Means to let the browser visit /index again.

Seven, template (html)

1. Set the template file directory

Add the template path (page file storage path) to the'DIRS' list in TEMPLATES in the project's setting.py

In setting.py, there is this variable by default:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

That is, the absolute path of the project. The relative path can be spliced ​​by this variable so that the template file can still be found after the project is moved.

Therefore, it can be written like this in'DIRS':

'DIRS': [os.path.join(BASE_DIR, 'templates')]

Note: Generally, a new folder with the same name as the application is created under templates, and the corresponding application templates are stored in this folder to separate application templates.

2. Use template files

Use template files in view functions (functions under views)

a) Get the template content

temp = loader.get_template('python/index.html')

b) Define the context

#context = RequestContext(request,{})

context = {替换字典}

c) Render the template

res_html = temp.render(context)

d) Return to the browser

return HttpResponse(res_html)

But django has its own render function, so it can be written directly as:

return render(request, "python/index.html", {"key":"value"})

The dictionary in the parameter can replace the content of the page. Use two curly brackets to enclose the variable { {}}, then the key corresponds to the variable name, and the value is the variable value to modify the page. Such as:

return render(request, "python/index.html", {"context":"让我们来试一试"})

 

To use a for loop in the page, use {%%}, such as:

{% for i in list %}

<li>{
   
   {i}}<li>

{% endfor %}

Note: You cannot use range directly, because range is a generator, not a list. You need to replace List with a list in the views, such as:

return render(request, "python/index.html", {"list":list(range(10))})

Read information from the database and display:

1.views.py

a) Get information from the template

book_list = Book.objects.all()

b) Replace page content

return render(request,"book/index.html", {"book_list":book_list})

2. Page traversal

{% for book in book_list %}

{
   
   {book}}

</br>

{% endfor %}

Eight, static file configuration

1. Create a static folder in the project

2. Modify setting.py

STATIC_URL = '/static/'

STATICFILES_DIRS = [os.path.join(BASE_DIR + "static")]

On html:

Originally written

{# <link rel="stylesheet" href="/static/css/reset.css"/>#}

Do not use path writing, it is convenient to change settings to configure static writing

Before the head:

{% load staticfiles %}

head:

<link rel="stylesheet" href="{% static "css/reset.css" %}"/>

<link rel="stylesheet" href="{% static "css/navigation.css" %}"/>

<link rel="stylesheet" href="{% static "css/register.css" %}"/>

 

Nine, template language and filters

Template language

1. Template variables

The template variable name is composed of numbers, letters, underscores and dots, and cannot start with an underscore.

Use template variables: { {template variable name}}

Parsing order of template variables:

For example: { {book.btitle }}

  1. First treat book as a dictionary and btitle as the key name, and take the value book['btitle']
  2. Regard book as an object and btitle as an attribute, and take the value book.btitle
  3. Regarding book as an object and btitle as an object method, take the value book.btitle

For example: { {book.0}}

  1. First treat book as a dictionary, and use 0 as the key name, and take the value book[0]
  2. Regard book as a list and 0 as a subscript, take the value book[0]

If the parsing fails, the template variable is filled with an empty string when the content is generated.

When using template variables, the front of. May be a dictionary, an object, or a list.

2 Template label

{% 代码段 %}
    for循环:
        {% for x in 列表 %}
        {
   
   {循环内容}}
    # 列表不为空时执行
        {% empty %}
    # 列表为空时执行
        {% endfor %}

The number of times the for loop has been traversed can be obtained by { {forloop.counter }}.

{% if 条件 %}

{% elif 条件 %}

{% else %}

{% endif %}

Logical operations are supported in the template, such as:

Relational comparison operators:> <>= <= == !=

Note: When performing comparison operations, there must be spaces on both sides of the comparison operator.

Logical operation: not and or

3. Template comments

Single line comment: #note content #}

Multi-line comments:

{% comment %}

注释内容

{% endcomment %}

 

filter

1. The use of filters

Filters are used to manipulate template variables.

date: Change the display format of the date.

length: Find the length. String, list.

default: Set the default value of the template variable.

format:

模板变量|过滤器:参数

Such as:

{
   
   {book.date|date:'Y年-m月-d日'}}

2. Custom filter

  1. Create a new python package named templatetags under app.
  2. Create a new py file in the templatetags package, the file name is not fixed, for example: filters.py
  3. Guide package
from django.template import Library

4. Create the Library object

register = Library()

5. Create a filter function and decorate

#定义函数,进行装饰,装饰后即成为过滤器

@register.filter

def mod(num):

'''判断参数是否为偶数'''

return num%2 == 0

The custom filter function has at least one parameter and at most two. When using a filter, the thing before "|" is passed to the filter as a parameter by default.

If there are two parameters, the thing before | is taken as the first parameter by default, add: after the filter, and write the second parameter after:. Such as:

{
   
   {book.date|date:'Y年-m月-d日'}}

Template inheritance

When multiple pages have the same content, template inheritance can be used to write the same part into the parent template, and the child template obtains the content of the parent template by inheriting the parent template.

When the child template inherits the parent template, use

{% extends '父模板路径' %}

The parent template path is the relative templates path. When inheriting, the code included by default when creating a new sub-template must be deleted. And it is invalid to write code directly in the sub-template.

When the child template needs to write code, you need to reserve a block in the parent template. The sub-template then rewrites the reserved block.

Blocks can be defined in the parent template, using tags:

{% block 块名 %}

中间内容(块中间可以写内容,也可以不写)

{% endblock 块名%}

After the child template inherits the parent template, it can rewrite the content of a block in the parent template.

Inheritance format:

{% extends 父模板文件路径%}

{% block 块名 %}

{
   
   { block.super}} #获取父模板中块的默认内容

Rewritten content

{% endblock 块名%}

Template escape

In views.py, when using the render function to replace the content of the template, if you use tags such as <h1><h1>, the string passed will not become a tag. So you need to turn off html escaping.

Such as:

HTML tags in the template context will be escaped by default.

小于号< 转换为<

大于号> 转换为>

单引号' 转换为'

双引号" 转换为 "

与符号& 转换为 &

Closing method:

1. Use filters

{
   
   { 模板变量|safe}}

2. Filter switch

{% autoescape off %}

模板语言代码

{% endautoescape %}

 

Guess you like

Origin blog.csdn.net/x950913/article/details/108655025