Python-Django-url routing and rendering template

Basic use

Project directory and file description

image-20230428120951687

manage.py A command line tool in django that manages the __init__.py empty file of the django project and tells python that this directory is a python package

setting.py Configuration file, including database information, debugging flags, static files, etc.

urls.py URL declaration of Django project

wsgi.py Used for deployment server

Simple test

  • Create new views.py in the project directory

  • from django.http import HttpResponse #响应前端页面对应的模块
    #视图函数
    def index(request):
        return HttpResponse('Hello World')
    
  • Open in urls.py

  • from django.contrib import admin
    from django.urls import path
    from . import views#同级目录下导入Views文件作为模块使用
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('index/', views.index),
    ]
    
  • image-20230428122942803

The role of urls.py

URL configuration (URLconf) is like the directory of websites supported by Django. Its essence is a mapping table between URL patterns and the view functions to be called for that URL pattern. This way you tell Django to call that code for that URL. The loading of the url starts from the configuration file

URL parameter passing and parameter limitation

No parameter restrictions

  1. views.py creates a new function as follows

  2. def names(request,name,age):
        return HttpResponse("名字:{},年龄:{}".format(name,age))
    
  3. in urls:

    urlpatterns = [
        path('admin/', admin.site.urls), path('inf/<name>/<age>',views.names)
    ]
    
  4. image-20230429132940030

  5. image-20230429133333291

Converter-parameter qualification

Default supported converters

str: matches a non-empty string except the path separator (/), this is the default form

int: matches positive integers, including 0.

slug: Matches a string consisting of letters, numbers, dashes, and underscores.

uuid: Match formatted uuid, such as 075194d3-6885-417e-a8a8-6c931e272f00.

path: matches any non-empty string, including path separators

  1. view.py

    def names2(request,name,age):
        return HttpResponse("名字:{},年龄:{}".format(name,age))
    
  2. urls.py

    urlpatterns = [
        path('admin/', admin.site.urls), path('inf2/<slug:name>/<int:age>',views.names2)
    ]
    
re_path regular matching
  1. Import modules in urls.py

  2. from django.urls import path,re_path
    
  3. Format

    urlpatterns = [
        path('admin/', admin.site.urls),
        re_path('^inf2/(?P<name>[A-z]{4,12})/(?P<age>[0-9][0-9])/$',views.names2)
    ]
    

    The relationship between projects and applications

image-20230428123151718

Create new APP

  1. ubuntu creates:python manage.py startapp +app名
  2. Note (must cddao to the project directory to use manage.py):image-20230428123900969

Register APP

Register in settings.py of the main project

image-20230429142028761

The role of include

image-20230429142807154

Need to be imported into the main project

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

APP-views.py

from django.http import HttpResponse #响应前端页面对应的模块
def yq(requests):
    return HttpResponse("这是言情小说")

The role of kwargs

Main urls.py file

from django.contrib import admin

from django.urls import path,include

urlpatterns = [

path(‘admin/’, admin.site.urls),

path(‘book/’,include(‘book.urls’),{‘switch’:‘true’}),

]

#book-views.py文件
def yq(requests,**kwargs):
    return HttpResponse(f"这是言情小说{
      
      kwargs['switch']}")

The role of name

used as redirect

  • book-view.py

    from django.shortcuts import render,redirect,reverse#导入重定向需要的两个模块
    
  • book-urls.py

    urlpatterns = [
        path('yq/',views.yq),
        path('yq_new/',views.yq_new,name='yq_new')
    ]
    

template rendering

  1. Create a new templates directory under the same level directory of the main project to store each template.

  2. Import in main project-settings.py

  3. import os
    
    BASE_DIR = Path(__file__).resolve().parent.parent #默认有的获取到总项目目录
    
  4. Add the templates path here:

  5. image-20230429173130036

  6. Load module

    from django.template.loader import get_template#加载html模板文件的路径
    
  7. under views.py

    def yq(requests,**kwargs):
        reg = get_template('book_yq.html')
        html = reg.render()#渲染
        return HttpResponse(html)
        #或者直接return render(requests,'book_yq.html')
    

Guess you like

Origin blog.csdn.net/jiuwencj/article/details/130442400