Detailed explanation of the use of DJango view of views and template of templates
- 2021-07-22 10:13:19
- OfStack
View
In django, views respond to WEB requests
The view receives the reqeust object as the first parameter, which contains the requested information
The view is an Python function defined in views. py
After defining the view, you need to configure urlconf, otherwise you cannot process the request
In Django, the definition of URLconf includes regular expression and view
Django uses a regular expression to match the requested URL. Once the match is successful, the view of the application is called
Note: Only the path part, that is, the string after removing the domain name and parameters, is matched
Insert booktest in test1/urls. py to connect the main urlconf to the booktest. urls module
View code
# views.py
# 1 A simple view , Fixed return hrllo world
def index(request):
return HttpResponse('hello world')
Template
Templates are html pages that populate values based on the data passed in the view
Templates and Applications booktest are sibling directories
Template structure templates/application name (booktest) /*. html
Splice the address information of the template in the DIRS value of TEMPLATES in the settings. py file: 'DIRS': [os. path. join (BASE_DIR, 'templates')],
urls code
Mode 1: Modify the original urls directly
# fanlie/fanlei/urls.py
from django.conf.urls import include, url
from django.contrib import admin
from booktest import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
# Called if the match is empty views.index Return to Home Page
url(r'^$',views.index),
]
Mode 2: Modify in the application directory
# fanlie/fanlei/urls.py
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
# Do nothing and go straight booktest.urls To find the corresponding match
url(r'^',include('booktest.urls')),
]
# fanlei/booktest/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
# js The end is to call the function in the view js
url(r'.*.js',views.js),
# Direct access to the representative is the home page , Call a function in the view index
url(r'^$', views.index),
# If it is image The representative at the beginning is a picture , Let directly DJango To open the corresponding picture and return
url(r'^images/(?P<path>.*)', 'django.views.static.serve', {'document_root':'/home/python/Desktop/fanlei/templates/booktest/images'}),
]
Views used in the above template
from django.shortcuts import render
def index(request):
# Returns the contents of a file in quotation marks
return render(request, 'booktest/index.html')
def js(request):
# Returns the contents of a file in quotation marks
return render(request,'booktest/jquery-1.12.4.js')