Python Web Development (Django)

Web application infrastructure: C/S and B/S architecture

1. Configure the Web development environment 

Create a virtual environment and run django in the virtual environment

 The python version running here is 3.7

// Time conversion source
pip3.7 install -i https://pypi.tuna.tsinghua.edu.cn/simple package_name

1.Update pip

python3.7 -m pip install --upgrade pip

2. Download virtualaienv

pip3.7 install virtualenv

3. Create new files for virtual environment applications 

4. New file created by cd (virtualenv)

5.

virtualenv env1
//env1新创建的虚拟环境

6.

cd env1
cd Scripts
//激化环境
activate
deactivate //退出

7.pip list can view the list of virtual environments

8. Download django (if you have two python environments and need to change the application, change the original one to python3.10, and change the current 3.7 to python3.7. At the same time, you need to copy a python3.7 application and rename it to python ), after downloading django, you can also use pip list to check whether django is available

pip install django==2.2.3

Create a Django project

1. First create a new folder pythonweb

2. Click Settings in the lower left corner, then click the first

3

Note: The following error may occur at this time:

 The solution is to copy the path of the virtual file and return to the terminal, then search for power shell in windows, run it as administrator, and execute the following command

set-ExecutionPolicy RemoteSigned

Finally, run the virtual file path in the vscode terminal, and it will appear

4. Create a django project:

django-admin startproject demo
cd demo
python manage.py runserver
//添加其他端口直接在后面加上就行

 Create an application in the project

Create app

python manage.py startapp hello

Activate app

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'hello',
]

Write view

Open the view file views.py under the application hello, and write the view function in it. The specific code is as follows:

from django.shortcuts import render
from django import http
def index(request):
    return http.HttpResponse('hello world')

Configure routing

mysite/urls.py (root route)

from django.contrib import admin
from django.urls import path,include
urlpatterns = [
    path('admin/', admin.site.urls),
    path('hello/',include('hello.urls')),
]

 mysite/hello/urls.py (sub-route)

from django.urls import path
from . import views
urlpatterns = [
	path('',views.index)
]

Start the development server and test application functions

2. Routing system 

1.Path() function

path(route,view,kwargs=None,name=None)

eg: path(‘blog’,views.blog)

         path(‘showblog/<article>/’,views.showblog)

  • route: a required parameter, a rule for matching URLs. It is a string that can contain capture parameters, identified by "<>". For example, in the second URL of the above example, <article>, article will be represented by the keyword The form of parameters is passed to the showblog() view.
  • view: required parameter, indicating the view function. After Django matches the URL pattern, it will call the corresponding view and pass in a django.http.HttpRequest object as the first parameter.
  • kwargs: Receive any number of keyword parameters in the URL address, organize them into a dictionary type data and pass it to the target view.
  • name: Give the URL pattern a name so that Django can uniquely reference it anywhere. It should be noted that when using the path() function to match URL patterns, the protocol type, domain name, and port number in the URL will not be matched.

2. Built-in routing converter

Root route:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('word/<str:word>/',views.index_word),
    path('num/<int:number>',views.index_num),
]
urlpatterns = [
    path('str/<str:str_type>', views.str_converter),              	      # 使用str转换器
    path('int/<int:int_type>', views.int_converter),       	      # 使用int转换器
    path('slug/<slug:slug_type>', views.slug_converter),  	      # 使用slug转换器
    path('uuid/<uuid:uuid_type>', views.uuid_converter),                  # 使用uuid转换器
    path('path/<path:path_type>', views.path_converter),                  # 使用path转换器
]

3. Custom routing converter

register_converter(converter, type_name)

  • converter: Receives a custom routing converter class.​  
  • type_name: Indicates the route converter name used in the URL.

 Create Django project chapter02, create application app01 in this project, and create a new converter.py file in application app01:


from django.urls import register_converter
class MyConverter:
    regex = '1[3-9]\d{9}'
    def to_python(self,value):
        return value
    def to_url(self,value):
        return value
register_converter(MyConverter,'mobile')

 Root route:

from django.urls import path
from app01 import converter,views   # 导入应用中的converter
urlpatterns = [
   path('mobile/<mobile:phone_num>/',views.show_mobile)
]

Define moblie view in app01 application: 

from django.http import HttpResponse
def show_mobile(request, phone_num):
    return HttpResponse(f'手机号为:{phone_num}')

4. Use regular expressions to match URLs

re_path(route, view, kwargs=None, name=None)

The parameter route of the re_path() function receives a regular expression, and the remaining parameters have the same effect as the parameters in the path() function.

The named regular expression format is: (?P<name>pattern), where name represents the group name and pattern represents the matching regular expression.

Create an app02 application and configure sub-routes:

Note that you also need to add the app02 application to the setting.


from django.urls import re_path
from . import views

urlpatterns = [
    re_path(r'^bio/(?P<bio>\w{5})/$',views.bio),
    # re_path(r'^bio/(?p<bio>\w{5})/(?p<bio2>\w{5})$',views.bio),
    re_path(r'^num_re/(\w{5})/(\w{5})$',views.num_re)
]

Root routing needs to be configured:



from django.urls import path
from app01 import converter,views
from django.urls import path,include
urlpatterns = [
    path('mobile/<mobile:phone_num>/',views.show_mobile),
    path('', include('app02.urls')),
    
]

Writing view file (in app02):

from django.shortcuts import render

# Create your views here.

from django.shortcuts import HttpResponse

# Create your views here.
def bio(request,bio):
    return HttpResponse(f'{bio+bio}')

def num_re(request,num_re,num_re1):
    return HttpResponse(num_re+num_re1)

5. Route distribution

There are two ways to use the include() function to implement route distribution:

include(module,namespace = None) # 1.Introduce the application

URLconf include(pattern_list)                         # 2. Introduce URL pattern list

  • module: used to specify the URLconf module.​  
  • namespace: The namespace used to specify the URL pattern instance.
  •  pattern_list: used to specify an iterable list of path or re_path instances.

# 根URLconf
urlpatterns = [
    path('blog/', include('app02.urls'),
    path('',include('app01.urls'))
                                       
]
# app02应用URLconf
urlpatterns = [
    path('archive/', views.archive),
    path('about/', views.about),
]

#表示url请求127.0.0.1:8000/blog/archive

6. Use reverse() to reversely parse the URL

reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None)

  •  viewname: URL pattern name or callable view object. required  
  • urlconf: A URLconf module containing URL patterns.​  
  • args: List type parameters passed to the URL.​  
  • kwargs: Dictionary type parameters passed to the URL.​  
  • current_app: The application to which the current view belongs.

Note that the parameters args and kwargs in the reverse() function cannot be used at the same time. The syntax in Django cannot be used elsewhere 

can be parsed in reverse direction url mode can also be parsed in reverse direction. Functions can also be parsed in reverse direction in templates URL

 Add to the root route:

from django.urls import path,include
path('app03/',include('app03.urls'))

Add urls to the new application app03

from django.urls import path
from app03 import views
urlpatterns = [
    # 反向解析url模式
    path('url-reverse/',views.get_url,name='url'),
    # 反向解析函数
    path('login/',views.login,name='login'),
    # 在模板中反向解析URL
    path('hello/',views.hello,name='hello'),

]

View file in app03:

Note that the hello function needs to be added to the setting:

Also add app03 to INSTALLED_APPS:

Also note that you need to create new templates in the chapter2 project

 Code in helloworld.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>hello world</h1>
    {% url 'login' %}

    <div>
        <a href="{% url 'login' %}">点击我</a>
    </div>
</body>
</html>
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',
            ],
        },
    },
]
from django.shortcuts import render

# Create your views here.
from django.shortcuts import reverse
from django.shortcuts import HttpResponse
def get_url(request):
    return HttpResponse(f"反向解析的url为:{reverse('url')}")
def login(request):
    return HttpResponse(f"反向解析的url为:{reverse('login')}")

def hello(request):
    return render(request,'helloworld.html')

 

7. Methods to implement page jumps

 href="{% url 'name' %}"

Create project HelloWorld

Create application app1

Note that you need to add app1 and the path of templates to the setting file.

Root path:

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


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

Subpath:

from django.urls import path
from app1 import views

urlpatterns = [
    path('python/',views.python_web,name='python'),
    path('about/',views.about,name='about'),
]

 views file:

from django.shortcuts import render

# Create your views here.
from django.shortcuts import  HttpResponse
def python_web(request):
    return render(request,'python.html')
def about(request):
    return render(request,'about.html')

python.html:

Note: The about represents the name of the file you need to jump to in the subpath.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>python-web</title>
</head>
<body>
    <a href="{% url 'about' %}">关于python web开发</a>
    
</body>
</html>

 about.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    Django 是一个由 Python 编写的一个开放源代码的 Web 应用框架。

使用 Django,只要很少的代码,Python 的程序开发人员就可以轻松地完成一个正式网站所需要的大部分内容,并进一步开发出全功能的 Web 服务 Django 本身基于 MVC 模型,即 Model(模型)+ View(视图)+ Controller(控制器)设计模式,MVC 模式使后续对程序的修改和扩展简化,并且使程序某一部分的重复利用成为可能。<br/>
<h2>
    <a href="{% url 'python' %}">返回首页</a>
</h2>
</body>
</html>

3. Model and database

1. Connect to the database environment

//虚拟环境
//创建项目
django-admin startproject chapter03
cd chapter03
python manage.py startapp books
//settings.py修改
installed apps:{
'books'
}
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test',
'HOST':'127.0.0.1',
'PORT': 3306,
'USER':'root',
'PASSWORD':'123456'
}
安装
mysql -uroot -p
create database test;
show databases;
//安装驱动程序
pip install mysqlclient
pip install .\mysqlclient-1.4.6-cp37-cp37m-win_amd64.whl
查找合适的 mysqlclient package

(2059 error report) encryption method change: https://www.cnblogs.com/ Beginner-Y/p/13798942.html  

(2026 error report)Solve the problem of django.db.utils.OperationalError: (2026, 'SSL connection error: unknown error number') under Windows_django.db.utils. operationalerror: (2026, 'ssl conn_Chebei IT Zai’s Blog-CSDN Blog

If it can start normally, the configuration is complete.
python manage.py runserver
models.py 文件里面进行设置
class BookInfo(models.Model):
name = models.CharField(max_length=20, verbose_name="名称")
pub_date = models.DateField(verbose_name="发布日期")
readcount = models.IntegerField(default=0, verbose_name="阅读量")
commentcount = models.IntegerField(default=0, verbose_name="评论量")
is_delete = models.BooleanField(default=False, verbose_name="逻辑删除")
def __str__(self):
    return self.name
//生成迁移文件
python manage.py makemigrations
//执行迁移文件
python manage.py migrate

Finally, check the mysql view software. If the following message appears, the configuration is successful.

2. Add data

Add it to the application models

from django.db import models

class BaseModel(models.Model):
    name = models.CharField(max_length=20, verbose_name="名称")
    pub_date = models.DateField(verbose_name="发布日期")

    class Meta:
        abstract = True

    def __str__(self):
        return self.name

class BookInfo(BaseModel):
    readcount = models.IntegerField(default=0, verbose_name="阅读量")
    commentcount = models.IntegerField(default=0, verbose_name="评论量")
    is_delete = models.BooleanField(default=False, verbose_name="逻辑删除")

    def __str__(self):
        return self.name

class ImageInfo(BaseModel):
    likecount = models.IntegerField(default=False, verbose_name="点赞量")

    def __str__(self):
        return self.name
//生成迁移文件
python manage.py makemigrations
//执行迁移文件
python manage.py migrate
python manage.py shell
#导入models的相关文件
from books.models import BookInfo
#增加数据
BookInfo.objects.create(name='三国演义',pub_date='1937-2',readcount=100,commentcount=70,is_delete=0)
#增加数据
a=BookInfo.objects.create(name='西游记',pub_date='2023-6-7',readcount=70,is_delete=0)
#可以查看数据
a.name

#save的方法增加数据

bookinfo=BookInfo(name='python',pub_date='1996-8-6',readcount=70,commentcount=67,is_delete=0)
bookinfo.save()

3. Query data

  • all() method: Query all records of the model in the database mapped table, the return value is oneQuerySet object, this object is a list-like structure that supports for loops, indexes (negative indexes are not supported), slicing and other operations.
  • filter() method: query the data table according to the query condition, return< a i=4>Data that satisfies conditions, the return value is a QuerySet object
  • exclude() method: Query the database according to the query condition, and returnnot satisfied Conditional data, the return value is aQuerySet object
  • get() method: Search according to the query conditions and return a record that meets the conditions. The return value is a model object.

models.py data:

from django.db import models

# 自定义管理器
class CountryManager(models.Manager):
    def country_name_prefix(self):
        # 查询所有结果
        all_countries = self.all()
        for country in all_countries:
            country.country_name = '国家' + country.country_name
        return all_countries

class Country(models.Model):
    country_code = models.CharField(max_length=20)
    country_name = models.CharField(max_length=50)
    objects = CountryManager()
    class Meta:
        db_table = 'country'


class PersonManager(models.Manager):
    def get_queryset(self):
        return super(PersonManager,self).get_queryset().filter(person_nation__exact=1)

# 一对多
class Person(models.Model):
    person_name = models.CharField(max_length=20)
    person_age = models.IntegerField(default=0)
    person_money = models.IntegerField(default=0)
    person_nation = models.ForeignKey(Country,on_delete=models.CASCADE,db_column='f')

    objects = PersonManager()
    class Meta:
        db_table = 'person'

class President(models.Model):
    president_name = models.CharField(max_length=70)
    president_gender = models.CharField(max_length=10)
    president_nation_id = models.OneToOneField(Country,on_delete=models.CASCADE,db_column='f')

    class Meta:
        db_table = "president"



    def __str__(self):
        return self.country_name


from django.db import models

class BaseModel(models.Model):
    name = models.CharField(max_length=20, verbose_name="名称")
    pub_date = models.DateField(verbose_name="发布日期")

    class Meta:
        abstract = True

    def __str__(self):
        return self.name

class BookInfo(BaseModel):
    readcount = models.IntegerField(default=0, verbose_name="阅读量")
    commentcount = models.IntegerField(default=0, verbose_name="评论量")
    is_delete = models.BooleanField(default=False, verbose_name="逻辑删除")

    def __str__(self):
        return self.name

class ImageInfo(BaseModel):
    likecount = models.IntegerField(default=False, verbose_name="点赞量")

    def __str__(self):
        return self.name
all()方法
from books.models import BookInfo
all_info=BookInfo.objects.all()
all_info
#<QuerySet [<BookInfo: 三国演义>, <BookInfo: 西游记>, <BookInfo: python>]>
all_info[0].name
#'三国演义'
info_list=[info for info in all_info]
info_list
#[<BookInfo: 三国演义>, <BookInfo: 西游记>, <BookInfo: python>]
info_list=[info.name for info in all_info]
info_list
#['三国演义', '西游记', 'python']

filter()方法
from books.models import BookInfo
book_info=BookInfo.objects.filter(id=3)
boo_info
#<QuerySet [<BookInfo: python>]>

exclude()方法
ex_info=BookInfo.objects.exclude(id=3)
ex_info
#<QuerySet [<BookInfo: 三国演义>, <BookInfo: 西游记>]>
ex_info[0].name
#'三国演义'
get()方法

book_obj=BookInfo.objects.get(id=3)
book_obj
#<BookInfo: python>
 book_obj.name
#'python'
values接受可选参数
all_info=BookInfo.objects.all().values()
all_info
#<QuerySet [{'id': 1, 'name': '三国演义', 'pub_date': datetime.date(1937, 1, 2), 'readcount': 100, 'commentcount': 70, 'is_delete': False}, {'id': 2, 'name': '西游记', 'pub_date': datetime.date(2023, 6, 7), 'readcount': 70, 'commentcount': 0, 'is_delete': False}, {'id': 3, 'name': 'python', 'pub_date': datetime.date(1996, 8, 6), 'readcount': 70, 'commentcount': 67, 'is_delete': False}]>
all_info=BookInfo.objects.values('name')
all_info
#<QuerySet [{'name': '三国演义'}, {'name': '西游记'}, {'name': 'python'}]>
all_info=BookInfo.objects.all().values_list('name')
all_info
#<QuerySet [('三国演义',), ('西游记',), ('python',)]>


order_by()方法
name=BookInfo.objects.order_by('id')
for i in name:
... print(i.name)
#或者
name
<QuerySet [<BookInfo: 三国演义>, <BookInfo: 西游记>, <BookInfo: python>]>

4. Delete data

delete()方法
book_obj=BookInfo.objects.get(id=1)
book_obj
#<BookInfo: 三国演义>
book_obj.delete()
#(1, {'books.BookInfo': 1})

5.Update data

res=BookInfo.objects.filter(id=2).update(is_delete=1)
res
#1

6.Multiple table query

Common operators:

1 to many forward query

Syntax: current model object.Related field.Field to be queried in the associated model

from books.models import Person
p=Person.objects.get(id=1)
p.person_name
#'小红'
country_name=p.person_nation.country_name
country_name
#'china'

Reverse query

Syntax: current model object.Associated model table name (lowercase)_set.all()

from books.models import Country
 c=Country.objects.get(id=1)
c 
#<Country: Country object (1)>
 p_country=c.person_set.all()
p_country

One to one

forward query

Syntax: current model object.Related field.Field to be queried in the associated model

from books.models import President
from books.models import Country
p=President.objects.get(id=1)
p.president_name
#'aa'
country_name=p.president_nation_id.country_name
country_name
#'china'

Reverse query

Syntax: Current model object. Associated model table name (lowercase). Fields to be queried in the associated model

c=Country.objects.get(id=1)
c.country_name
#'china'
c.president.president_name
#'aa'

F object, Q object

from books.models import BookInfo
from django.db.models import F,Q
BookInfo.objects.filter(readcount__gt=F('commentcount'))
#<QuerySet [<BookInfo: 三国演义>, <BookInfo: python>]>
BookInfo.objects.filter(Q(readcount__gt=10) & Q(id__lt=3))
#<QuerySet [<BookInfo: 西游记>, <BookInfo: 三国演义>]>
BookInfo.objects.filter(Q(readcount__gt=10) | Q(id__gt=2))
#<QuerySet [<BookInfo: 西游记>, <BookInfo: 三国演义>, <BookInfo: python>]>
BookInfo.objects.filter(~Q(readcount__lt=80))
#<QuerySet [<BookInfo: python>]>

7. Aggregation function

 from django.db.models import Avg,Min
BookInfo.objects.aggregate(Avg('readcount'),Min('commentcount'))
#{'readcount__avg': 78.3333, 'commentcount__min': 65}
BookInfo.objects.aggregate(avg=Avg('readcount'),min=Min('commentcount'))
#{'avg': 78.3333, 'min': 65}

4. Template

1. Use template files

Note: templates need to be recommended in the application and at the same level as the app

View file:

from django.shortcuts import render
from datetime import datetime
from django.http.response import HttpResponse
# Create your views here.

# get_template
from django.template.loader import get_template
# 准备数据
time2 = datetime.today()
def demo1(request):
    # 载入模板文件
    t = get_template('time.html')
    # 渲染模板
    html = t.render({'time':time2})
    return HttpResponse(html)

# render_to_string
from django.template.loader import render_to_string
def demo2(request):
    str_response = render_to_string('time.html',{'time':time2})
    return HttpResponse(str_response)

# TemplateResponse
from django.template.response import TemplateResponse
def demo3(request):
    return TemplateResponse(request,'time.html',{'time':time2})

# render
def demo4(request):
    return render(request,'time.html',{'time':time2})

def demo5(request):
    add1 = [1,2,3]
    add2 = [4,5,6]
    time = datetime.now()
    value = [{'name':'张三','age':17},{'name':'李四','age':34},{'name':'王五','age':35}]
    c = {'a':5,'b':add1,'second':add2,'c':"I don't know",'d':'laura','f':'he ll o w','g':time,'h':'','i':value,'j':'<a&sd>',}
    return render(request,'demo5.html',c)

Subroutes:

from app1 import views
from django.urls import path

urlpatterns = [
    path('demo1/',views.demo1),
    path('demo2/',views.demo2),
    path('demo3/',views.demo3),
    path('demo4/',views.demo4),
    path('demo5/',views.demo5),
]

Root route:

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

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

time.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>{
   
   {time}}</h1>
</body>
</html>

 

 2. Variables

{ { variable }}

Template variable names consist of letters, numbers, and underscores ("_"), but cannot begin with an underscore.

Filters are used to filter variables to obtain more precise data

{ { variables|filters }}

filter:

 View file:

def demo6(request):
    a = {'k':123456789,'l':[1,2,4],'m':12,'n':'asdfg','o':'ASFG','p':[2,4,6,8],'q':'hello world'}
    return render(request,'demo6.html',a)

Subroutes:

path('demo6/',views.demo6),

demo6.html file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p>
        filesizeformat:{
   
   {k|filesizeformat}}<br/>
        join:{
   
   {l|join:"//"}}<br/>
        linenumbers:{
   
   {m|linenumbers}}<br/>
        length:{
   
   {n|length}}<br/>
        lower/upper:{
   
   {o|lower}}<br/>
        random:{
   
   {p|random}}<br/>
        truncatewords:{
   
   {q|truncatewords:2}}
        

    </p>
</body>
</html>

demo5.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p>
        add1:{
   
   {a|add:'32'}}<br/>
        add2:{
   
   {b|add:second}}<br/>
        addslashes:{
   
   {c|addslashes}}<br/>
        capfirst:{
   
   {d|capfirst}}<br/>
        cut:{
   
   {f|cut:""}}<br/>
        date:{
   
   {g|date:"Y年m月d日"}}<br/>
        default:{
   
   {h|default:"35"}}<br/>
        dictsort:{
   
   {i|dictsort:"age"}}<br/>
        escape:{
   
   {j|escape}}<br/>
        

    </p>
</body>
</html>

 

3. Label

{% day %}    ... {% end day %}

for

demo7.html file:

{% for m in data %}
<li>{
   
   {m}}</li>
{% endfor %}

demo8.html file:

<p>
        {% for r in data %}
        第{
   
   {forloop.counter}}行:
        {% for a in r %}
        <li>{
   
   {a}}</li>
        {% endfor %}
        {% endfor %}
    </p>

demo9.html file:

 <p>
        {% for k,v in data.items %} 
        <li>{
   
   {k}}={
   
   {v}}</li>
        {% endfor %} 
        
    </p>

 demo_f.html text:

{% for r in data %}
<li>{
   
   {r}}</li>
{% empty %}
<li>抱歉,图书列表为空</li>
{% endfor %} 

 View file:

from django.shortcuts import render
from datetime import datetime
from django.http.response import HttpResponse

#遍历
def demo7(request):
    data = ['西游记','水浒传','三国演义']
    return render(request,'demo7.html',{'data':data})

#双层遍历
def demo8(request):
    data = [[1,2,3],['s','f','g'],[8,9,0]]
    return render(request,'demo8.html',{'data':data})

#遍历字典
def demo9(request):
    data = {'name':'张三','age':18}
    return render(request,'demo9.html',{'data':data})

#empty就像elif
def demo_for(request):
    data = [1,'',4]
    return render(request,'demo_f.html',{'data':data})

Subroutes:

from app1 import views
from django.urls import path

path('demo7/',views.demo7),
path('demo8/',views.demo8),
path('demo9/',views.demo9),
path('demo_f/',views.demo_for),

 

if/elif/else

demo11.html file:

<p>
        分数:{
   
   {data}}
        班级:{
   
   {clsl}}
        {% if data >= 90 %}
        等级A
        {% elif data >= 80 %} 
        等级B
        {% elif data >= 60 %} 
        等级C
        {% else %} 
        {% endif %} 
        
    </p>

View file:

def demo11(request):
    data = 79
    clsl = 277
    return render(request,'demo11.html',{'data':data,'clsl':clsl})

Subroutes:

path('demo11/',views.demo11),

4.Inheritance

in app1 application

Subroutes:

from app1 import views
from django.urls import path

urlpatterns = [
   
    path('base/',views.show_base),
    path('detail/',views.show_detail),
]

 View file:

from django.shortcuts import render
from datetime import datetime
from django.http.response import HttpResponse

def show_detail(request):
    return render(request,'detail.html')

def show_base(request):
    return render(request,'base.html')

base.html text:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}页面标题{% endblock %} </title>

</head>
<body>
    {% block header %} 
    <h1>标题</h1>
    {% endblock header %} 
    {% block main %} 
     <h2>页面内容</h2>
     {% endblock %} 
     <br/>
     {% block footer %} 
     <div class="footer no-mp">
        <div>
            <a href="#">关于我们</a>
            <span></span>
            <a href="#">联系我们</a>
            <span></span>
            <a href="#">招聘人才</a>
            <span></span>
            <a href="#">友情链接</a>
            <span></span>
        </div>
        <p>版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
            本文链接:https://blog.csdn.net/m0_74421072/article/details/134264782
            
           </p>

     </div>
     {% endblock %} 
     
</body>
</html>

detail.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    {% extends 'base.html' %} 
    {% block title %} 
    列表页面
    {% endblock %} 
    {% block header %} 
    <h1>书单</h1>
    {% endblock header %} 
    {% block main %}
    <a href="#">《鲁迅全集》</a>
    <a href="#">《秋雨散文集》</a>
    <a href="#">《黑暗森林》</a>
    <a href="#">《月亮与六便士》</a>
    {% endblock main %} 
    

</body>
</html>

5. View

Return date:

View file: (in the chapter5/views.py file in the chapter5 project)

from django.http import HttpResponse
from datetime import date
def showData(request,urlData):
    d = date.today()
    s = 'url路径中的数据:%s<br/>当前日期:%s' %(urlData,d)
    return HttpResponse(s)

url.py root route:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('test<urlData>',views.showData),
]

 verify:

get request

View file:

from django.http import HttpResponse
from datetime import date

def showGetData(request):
    s = '请求上传数据:名字=%s,年龄=%s' %(request.GET['name'],request.GET['age'])
    return HttpResponse(s)

Root route:

path('get',views.showGetData),

verify:

Download txt file

View file:

def downloadFile(request):
    r = HttpResponse('文件内容',content_type = 'text/text ;charset=utf-8')
    r['Content-Disposition'] = 'attachment;filename="test.txt"'
    r.write('\n<h1>test</h1>')
    return r

Root route:

path('txt/',views.downloadFile),

 verify:

 

csv file 

View file:

import csv
def writecsv(request):
   r = HttpResponse(content_type = 'text/text ;charset=utf-8')
   r['Content-Disposition'] = 'attachment;filename="data.csv"'
   w = csv.writer(r)
   w.writerow(['one',1,3,5])
   w.writerow(['two',3,66,8])
   return r

 Root route:

path('csv/',views.writecsv),

verify:

 

pdf file 

View file:

# pip install reportlab
def writepdf(request):
    from reportlab.lib.units import cm
    from reportlab.pdfbase.ttfonts import TTFont
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfgen import canvas
    from reportlab.lib.colors import red
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment;filename="data.pdf"'
    pdfmetrics.registerFont(TTFont('songti','simsun.ttc'))
    c = canvas.Canvas(response,pagesize=(10*cm,5*cm))
    c.setFont('songti',18)
    c.setFillColor(red)
    c.drawString(0.5*cm,4*cm,'python web简明教程')
    c.showPage()
    c.save()
    return response

Root route:

path('pdf/',views.writepdf),

verify:

 

json format

View file:

from django.http import JsonResponse
def writejson(request):
    return JsonResponse({'name':'张三','data':[123,'abc']})

Root route:

path('json/',views.writejson),

verify:

 

Data paging

 Connect to the database and pay attention to the data in the setting

Create a new application app

models.py file: execute later file migration

from django.db import models

# Create your models here.
class user(models.Model):
    name = models.CharField(max_length=20)
    age = models.IntegerField()

    

View file:

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
from . import models
def useModels(request):
    uname = request.GET['name']
    uage = request.GET['age']
    models.user.objects.create(name=uname,age=uage)
    s = '默认数据库中的user表数据:<br><table><tr><td>id</td><td>name</td>age</td></tr>'
    for u in models.user.objects.all():
        s+='<tr><td>%s</td><td>%s<td><td>%s</td></tr>'%(u.id,u.name,u.age)
    return HttpResponse(s+'</table>')

Subroutes:

from django.urls import path
from app import views

urlpatterns = [
    path('shuju/',views.useModels),
]

 Root route:

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

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

verify:

 

Data paging template

View file:

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from django.views import View

class testclassView(View):
    def get(self,request):
        return render(request,'classview.html',{'method':'GET'})
    def post(self,request):
        out = request.POST['DATA']
        return render(request,'classview.html',{'out':out,'method':'POST'})
    

Template file:

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>使用基于类的视图</title>
</head>
<body>
    <h1>使用基于类的视图</h1>
    <hr/>
    <form action="" name="input" method="post">
        {%csrf_token%} 
        请求方法:{
   
   {method}}<br/>
        请输入数据:<input type="text" name="DATA"><br/>
        <input type="submit" value="提交">

    </form>
    上传的数据为{
   
   {out}}

</body>
</html>

 Sub-route:

from django.urls import path
from app2 import views
from django.views.decorators.csrf import csrf_exempt
 
urlpatterns = [
    
    path('testview',views.testclassView.as_view())
    
]

 Same as root route

 

     

Guess you like

Origin blog.csdn.net/m0_74421072/article/details/134264782