程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Django] development: template language

編輯:Python

Django Frame design pattern

  • MVC Design patterns
    • MVC representative Model-View-Controller( Model - View - controller ) Pattern .
    • effect : Reduce the coupling between modules ( decoupling )
    • MVC
      • M The model layer (Model), It is mainly used to encapsulate the database layer
      • V View layer (View), Used to present results to users
      • C control (Controller , Used to process requests 、 get data 、 Return results ( important )
    • MVC The mode is shown in the figure :
  • MTV Pattern MTV representative Model-Template-View( Model - Templates - View ) Pattern . This pattern is used for hierarchical development of applications
    • effect : Reduce the coupling between modules ( decoupling )
    • MTV
      • M – The model layer (Model) Responsible for interacting with the database
      • T – Formwork layer (Template) Responsible for rendering content to the browser
      • V – View layer (View) Is the core , Responsible for receiving requests 、 get data 、 Return results
    • MTV The mode is shown in the figure :

notes :MTV The essence of is MVC, It can be understood as MVC+T, Use T To help show the content of the website . Because web pages C Most of the time, they are not big , It doesn't need to be split , So it becomes MTV 了 .

Templates Templates

  • What is a template
    1. Templates can be dynamically changed according to dictionary data html Webpage
    2. The template can dynamically generate the corresponding dictionary data according to the dictionary data passed in the view HTML Webpage .
  • Template configuration
    • Create template folder < Project name >/templates
    • stay settings.py in TEMPLATES Configuration item
      1. BACKEND : Specify the engine for the template
      2. DIRS : Search directory for templates ( It can be one or more )
      3. APP_DIRS : Whether to use in the application templates Search for template files in folders
      4. OPTIONS : Options for templates
  • The default module folder templates
  • modify settings.py file , Set up TEMPLATES Of DIRS The value is 'DIRS': [os.path.join(BASE_DIR, 'templates')],
# file: settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 'DIRS': [],
'DIRS': [os.path.join(BASE_DIR, 'templates')], # Add template path
'APP_DIRS': True, # Whether to index each app Inside templates Catalog
...
},
]

Loading method of template

adopt loader Access to the template , adopt HttpResponse To respond

from django.template import loade
# 1. adopt loader Load template
t = loader.get_template(" Template file name ")
# 2. take t convert to HTML character string
html = t.render( Dictionary data )
# 3. Use the response object to return the converted String content to the browser
return HttpResponse(html)

Use render() Directly load and respond to the template

from django.shortcuts import rende
return render(request,' Template file name ', Dictionary data )

Django Template language

Template parameters

  • Template parameter transfer refers to the formation of data into a dictionary , Pass parameters to template , Provide data for template rendering

Use loader Load template

t = loader.get_template('xxx.html')
html = t.render( Dictionary data )
return HttpResponse(html)

Use render Load template

return render(request,'xxx.html', Dictionary data ) 

Template variables

Use variable syntax in templates

  • {{ Variable name }}
  • {{ Variable name .index }}
  • {{ Variable name .key}}
  • {{ object . Method }}
  • {{ Function name }}

The variables in the view function must be encapsulated in the dictionary before they can be passed to the template

def xxx_view(request)
dic = {
" Variable 1":" value 1",
" Variable 2":" value 2",
}
return render(request, 'xxx.html', dic)

If there are too many variables , have access to locals () Automatically generate a dictionary of local variables

def xxx_view(request)
Variable 1 = value 1
Variable 2 = value 2
...
return render(request, 'xxx.html', locals())

XSS attack

Definition :XSS The full name is Cross Site Scripting Cross site scripting

principle : Malicious HTML/JavaScript The code is injected into the web page visited by the injured user , So as to achieve the purpose of attack

harm : Stealing user information , Destroy the normal operation of the website, etc

classification :

reflective xss

​ Definition : When a request is made ,XSS The code appears in URL in , Submit to the server as input , The server responds after parsing ,XSS The code is passed back to the browser along with the response content , Finally, browser parsing is executed XSS Code . This process is like a reflection , So it's called reflex type XSS

 Examples :
Submit as a query string xss Code
http://127.0.0.1:8000/test_html?t=<script>alert(11)</script>
After the backend receives the value of the query string , Show on page 
Storage type xss

​ Definition : The submitted XSS The code will be stored on the server side ( database , Memory , File system, etc ), Other users are attacked when they request the target page

 Examples :
When a blog posts , Submit XSS Code , After the server stores the code , When other users access this article , By XSS attack 
DOM xss

​ Definition :DOM XSS Your code doesn't need to interact with the server , Directly trigger the attack at the front end

 Examples :
Address bar submit # Content , for example -http://127.0.0.1:8000/test_html#javascript:alert(11)
Add... To the page JS:
<script>
var hash = location.hash;
if(hash){
var url = hash.substring(1);
location.href = url;
}
</script>

The label of the template

For documentation, see :https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#built-in-tag-reference

effect

  • Embed some server-side functions into the template

Tag syntax

{% label %}
...
{% End tag %}

if label

{% if Conditional expression 1 %}
...
{% elif Conditional expression 2 %}
...
{% elif Conditional expression 3 %}
...
{% else %}
...
{% endif %}

if Boolean operators in tags

  • if Operators that can be used in conditional expressions ==, !=, <,>, <=, >=, in, not in, is, is not, not、and、o
  • stay if Using actual parentheses in tags is invalid syntax . If you need them, indicate the priority , Nested... Should be used if Mark .

for label

grammar

  • {% for Variable in Iteratable object %}
  • ... Loop statement
  • {% empty %}
  • ... Statement to be filled when the iteratable object has no data
  • {% endfor %}

Built-in variables - forloop

filter

effect

  • The value of the variable is processed when the variable is output
  • By using Filter to change the output display of variables .

grammar

  • {{ Variable | filter 1: Parameter values 1| filter 2: The number 2 ... }}

Common filters

For documentation, see :

  • https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#built-in-filter-reference

Inheritance of templates

  • Template inheritance can reuse the content of the parent template , The child template directly inherits all the contents of the parent template and can overwrite the corresponding blocks in the parent template
  • Define blocks in the parent template block label

Identify which sub modules are allowed to be modified

block label : Define... In the parent template , You can override... In a sub template

{% block block_name %}
Define template blocks , This template can be covered by the same name block redefined by the sub template
{% endblock block_name %}
  • Inherit templates extends label ( Write in the first line of the template file )

The sub template inherits the syntax tag

  • {% extends ' Parent template name ' %}
  • Such as :

{% extends 'base.html' %}

Sub template Rewrite the content block in the parent template

{% block block_name %}
The child template plate is used to cover the parent template block_name Block content
{% endblock block_name %}

Overridden override rules

  • Don't rewrite , Will be displayed according to the effect of the parent template
  • rewrite , Will be displayed according to the rewriting effect

Be careful

  • When the template inherits , Server side dynamic content cannot be inherited

Reference documents

  • https://docs.djangoproject.com/en/2.2/ref/templates/language/#for-template-blocks

Example of template inheritance :

url Reverse DNS

url Reverse parsing refers to the use of the in a view or template , use path Define the name to find or calculate the corresponding route

path Syntax of functions

  • path (route, views, name=“ Alias ”)
  • for example :

path(‘page’, views.page_view, name=“page_url”)

path () Of name Key parameters

  • effect :

according to path Medium name= Pass the keyword to url Identified a unique name , In a template or view , You can infer this from the name url Information

  • In the template -> adopt url The label realizes the reverse resolution of the address
{% url ' Alias ' %}
{% url ' Alias ' ' Parameter values 1' ' Parameter values 2' %}
give an example :
{% url 'pagen' '400' %}
{% url 'person' age='18' name='gxn' %}
  • In the view function -> Callable django Medium reverse Method
from django.urls import reverse
reverse(' Alias ', args=[], kwargs={})
give an example :
print(reverse('pagen',args=[300]))
print(reverse('person',kwargs={'name':'xixi','age':18}))

Find the most suitable 【 The parameters are the same 】; When the parameters are consistent , Find the last one ;


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved