Template template configuration steps
- Create a Templates folder in the current working directory
- Configure the settings. py file
Middleware = ['django. middleware. security. securitymiddleware ', 'django. contrib. sessions. middleware. sessionmiddleware ', 'django. middleware. common. commonmiddleware ', # 'django. middleware. csrf. csrfviewmiddleware ', # comment this sentence, and no 403 error will be reported 'django. contrib. auth. middleware. authenticationmiddleware ', 'django. contrib. messages. middleware. messagemiddleware ', 'django. middleware. clickjacking. xframeoptionsmiddleware ',]
Templates = [{'backend': 'django. template. backends. django. djangotemplates ', 'dirs': [OS. path. join (base_dir, 'templates')], # configure the project path, which means that the current template path is the Templates folder created under the current project directory, base_dir settings. '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 ',] ,},},]
Template usage steps
(1) Add a new URL in URLs. py to display data.
(2) create a view Function
Def all_stu (request): If request. method = 'get': stus = student. objects. all () return render(request,'stus.html ', {'students': stus}) # In page rendering, the first parameter is the request, the second parameter is the page to be displayed, and the third parameter must be input into the dictionary
(3) create an HTML file named stus In the templates directory.
<! Doctype HTML> <HTML lang = "en">
(4) add an HTML page named info under the templates file directory
<! Doctype HTML> <HTML lang = "en">
(5) add view functions submitted to the database in the view.
Def add_info (request): # method to obtain the request HTTP method if request. method = 'get': Return render(request,'info.html ') # click the link request URL to jump to the info page if request. method = 'post': # obtain the mobile phone number and address submitted on the page, and save phone = request. post. get ('phone') Address = request. post. get ('address') # request. post. get the data stu_id = request. get. get ('stu _ id') # request. get. get the stu_id studentinfo after the request URL. objects. create (Phone = phone, address = address, stu_id = stu_id) return httpresponse ('success ')
After completing the preceding steps, you can complete the presentation with a simple template.
Django template rough use