Django

  • Introduction to Django Templates
    • The template path
    • Import the HTML
  • Template variables
  • Module Language (DTL)
    • Adding code Templates
    • For and if tags
    • Url tag
  • Template filter
    • Add (stitching)
    • The join (stitching)
    • Silce (slice)
    • The cut (remove)
    • The date (time)
    • Default (Default value)
    • Flast (returns the first element) and last(returns the last element)
    • Floatformat (remove)
    • Length (get length)
    • Lower (cast to be careful) and upper(cast to uppercase)
    • Safe (Marking the security string)
    • Striptags (Delete tags)
    • Truncatechars (specified length)
  • Template to optimize
    • The introduction of the template
    • Inherited template
      • How to use the parent template
      • How to use a subtemplate
  • Importing static files
    • Settings. py file Settings
    • The introduction of the sample


Introduction to Django Templates

Django uses the MVT model, and templates are the T: Templates template in MVT, which is what sets Django apart from regular MVC models. Templates are a bridge between the front and back ends, and Django relies on templates to pass parameters to the front end. Now I’m going to show you where templates are usually placed and how to make.html and.py interact with each other.

The template path

The template path is not an absolute rule, but a rule that most people follow. Templates are usually placed under the nametemplatesAnd this file can be placed in two locations, respectively in the root directory of the project, or in the root directory of the APP (generally, the page in the root directory of the project will have higher priority than the page in the APP).

If you create a project using PyCharm, templates in the root directory will be created automatically, andos.path.join(BASE_DIR, 'templates')The templates file in your APP needs to be registered manually in the listINSTALLED_APPSAdd the APP name, but make sure'APP_DIRS': True,(True is the default option)

Import the HTML

There are also two ways to import HTML into Python. The following information does not contain information about how to route, which can be found in Djangos Routing Details

  1. Method 1: Usefrom django.template.loader import render_to_string
from django.template.loader import render_to_string
from django.http import HttpResponse


Create a view here.
def home(request) :
    html = render_to_string('home.html')
    return HttpResponse(html)
Copy the code

This method is rarely used and will not be explained in detail, but in most cases we import HTML 2 using the following method. Approach 2: Use from Django.Shortcuts Import Render

from django.shortcuts import render


Create a view here.
def home(request) :
    return render(request, 'home.html')
Copy the code

Compared to the first approach, we found that the second approach made the code more concise and readable.

Template variables

Variables can simply be thought of as passing values, using templates. In Python, you need to use the context property, which is the property of render and render_to_string. Add the {{dictionary key}} template variable to the Python part of HTML: Use context= dictionary (context must be passed as a dict data type). If you need to pass a list or tuple or other type of value, pass it as a dictionary key. The key of the dictionary here can even pass through a class

from django.shortcuts import render


class MyName:
    def __init__(self, name) :
        self.name = name

    def get_name(self) :
        "" "" ""
        return 'I'm a class method'


xunmi = MyName('I'm a class property')

data = {
    'nickname': 'looking for'.'dictionary': {
        Key '1': 1.Key '2': 2,},'list': [
        'one'.2.'三'].'class': xunmi
}


Create a view here.
def home(request) :
    # html = render_to_string('home.html')
    return render(request, 'home.html', context=data)
Copy the code

Template variable HTML: receive using {{dictionary keys}} as follows (if you are a front-end, you can use {{}} to receive variables where you need to use {{}} in advance, and then want to ask the backend dictionary keys to fill in can pass values in advance)

<! DOCTYPEhtml>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>home</title>
</head>
<body>
    <h1>This is the {{nickname}} home page</h1>
    <h1>{{dictionary. keys}}{{dictionary. values}} you can use attributes such as keys and values</h1>
    <h1>This is the list :{{list}}</h1>
    <h1>This is the first element of the list :{{list.0}}</h1>
    <h1>This is the second element of the list :{{list.1}}</h1>
    <h1>This is the third element of the list :{{list.2}}</h1>
    <h1>This is a class attribute :{{class.name}}</h1>
    <h1>This is a class method :{{class.get_name}}</h1>
</body>
</html>
Copy the code

Module Language (DTL)

When writing these variables, it would be a bit of a hassle if we needed to take the keys to a list or other iterable. Using the for statement would be a great help.

Adding code Templates

The code templates are purely for later use. Django templates come with PyCharm pro. If you are not using PyCharm pro, you can add them in your Settings



We can add several common templates, such as if and for

# if the template
{% if $VARIABLE$ %}
$END$
{% endif %} 
# for the template
{% for $VAR$ in $COLLECTION$ %}
$END$
{% endfor %}
Copy the code

After adding the template, if we need to use the corresponding abbreviation, and then press TAB, it will automatically complete

For and if tags

For is not the same as if in Python, except that it needs to be wrapped with {% tag %}. The only difference between HTML and Python is that we need to use a closing tag at the end of the loop, where the if tag is {% endif %} and the for tag is {% endfor %}. In the for loop, the template language provides some variables to use

variable role
forloop.counter Number of current cycles (counting from 1)
forloop.counter0 Subscript of the current loop (evaluated from 0)
forloop.revcounter Number of remaining cycles (counting from total cycles)
forloop.revcounter0 Number of remaining cycles (calculated from total number of cycles -1)
forloop.first Whether it is the first loop
forloop.last Whether this is the last loop
forloop.parentloop Output information about the parent loop (number of cycles, number of remaining cycles, whether it is the first and last cycle, if the parent loop has a parent, it will be output together)
<! DOCTYPEhtml>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>home</title>
</head>
<body>{% for foo in list %} {% for foo1 in dictionary %} {% for foo2 in nickname %}<p>{{ forloop.parentloop }}</p>
                <p>{{ foo2 }}</p>
            {% endfor %}
            <p>{{ foo1 }}</p>
        {% endfor %}
        
        {% if foo == '2' %}
            <h3>I'm a thick bastard</h3>
        {% else %}
            <p>I am the list :{{foo}}</p>
        {% endif %}
    {% endfor %}
</body>
</html>
Copy the code

Again, notice that break and continue in the for loop are not available, and there is no whlie loop

Url tag

The URL tag will be one of the most commonly used tags, and although we can kill tags in the page, a smart programmer will never do that, because it will not be easy to maintain later. In this case, urls are similar to the inversion mechanism in Djangos routing. We need to write name in the path and then jump based on that name. We can also jump with parameters. Python code for the URL tag (in the urls.py file in the Django project APP):

from django.urls import path
from . import views

app_name = 'front'

urlpatterns = [
    path('home/', views.home, name='home'),
    path('home/<items>/', views.home, name='home'),
    path('index/', views.index, name='index'),]Copy the code

The code in the views.py file in Django project APP

from django.shortcuts import render


Create a view here.
def home(request, items='Default value') :
    # html = render_to_string('home.html')
    data = {'parameters': items}
    return render(request, 'home.html', context=data)


def index(request) :
    uid = request.GET.get('id')
    data = {'parameters': uid}
    return render(request, 'index.html', context=data)
Copy the code

Home.html in the HTML of the URL tag:

<! DOCTYPEhtml>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>home</title>
</head>
<body>

<h1>Returned with "{{parameters}}"</h1>
<a href="{% url 'front:index' %}">Order me right now</a>
<br>
<a href="{% url 'front:index' %}? id=1">I'm a question mark passer</a>

</body>
</html>
Copy the code

index.html:

<! DOCTYPEhtml>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>I'm a test page</title>
</head>
<body>

    <p>I really am a test page, don't come</p>{% if parameter %}<h1>You inserted the parameter "{{parameter}}" into me</h1>
    {% endif %}
    <a href="{% url 'front:home' 'location parameter' %}">Press me to jump back (position parameter)</a>
    <br>
    <a href="{% url 'front:home' items=' %}">Press me to jump back (keyword parameter)</a>
    
</body>
</html>
Copy the code

Template filter

The purpose of a filter is to filter the parameters passed to an HTML page, leaving the useful ones behind. This can be done in Python code, but sometimes it is better to put filters in HTML. Template import defaultfilters from Django. template import defaultfilters.

Add (stitching)

This concatenation is mainly used for string (STR) and integer (int), float (float) is automatically converted to integer (int), decimal part is automatically omitted. Concatenate the incoming value to the original value. This filter is smart. If both variables are numbers, it adds them, whether they are integers or not (string numbers are automatically converted to integers) and concatenates characters if they are strings. Note that Python is strongly typed, so different character types cannot be added. For example, if 2+’ billion ‘is null, it must be written as ‘2’+’ billion ‘!

<! -- list.1: '2'; Dictionary. Key 2:2 -->
<p>I was add filters: '{{list. 1 | add: in the dictionary. Key 2}} 'or' {{' 3 '| add:' $'}} '</p>
Copy the code

The join (stitching)

Concatenation of iterable objects (such as lists, tuples, strings) is analogous to join in Python

<! -- list =['one', '2', '3 ']-->
<p>I am join filter: {{list | join: '-'}}</p>
Copy the code

Silce (slice)

Similar to the Python slicing of iterable objects such as lists, the format is (start: end: step). For example, the following slicing successfully splits two commas

<! --' Slice using ': 'Hello, I am looking for '-->
<p>I am a slice filter: {{slice using | slice: '2:6:3'}}</p>
Copy the code

The cut (remove)

Removes all strings specified in the value, similar to reqlace(args, ‘) in Python.

<! -- Nickname: 'Looking for '-->
<p>I was cut filter: '{{nickname | the cut:' find '}} '</p>
Copy the code

The date (time)

Formats a date into a string in the specified format

<! --' time ': datetime.now(), datetime.now() is a Python library method that reads the current time. The format (/ :) can be customized -->
<p>I am the date filters: the original style - '{{time}}' filters converted - '{{time | date:' Y/m/d G: I: s'}} '</p>
Copy the code
Common format characters describe The sample
Y Four-digit year 2020
m Two-digit month 01-12
n One – or two-digit month 1-12
d Two digit days 01-31
j One – or two-digit days 1-31
g Twelve-hour hours prefixed with 0 01-12
h Twelve-hour hours without the prefix 0 1-12
G The 24-hour hour prefixed with 0 00-23
H The 24-hour hour without the prefix 0 0-23
i Minutes prefixed with 0 00-59
s Seconds prefixed with 0 00-59

Default (Default value)

The default value provided by default is used when the value is evaluated as Falst ([],{},None,Falst, etc are evaluated as Falst).

<! - null = None - >
<p>I am a default filter: {{null | default: 'here no value'}}</p>
Copy the code

Flast (returns the first element) and last(returns the last element)

Return object iteration the first element of the | the last element

<! -- list =['one', '2', '3 ']-->
<p>I am the first and the last filter: a list of the first element - {{list | first}} | list the last element - {{list | last}}</p>
Copy the code

Floatformat (remove)

Format a floating-point type by rounding it (one decimal is reserved by default, or integers if the decimal part is all zeros, followed by the number of digits specified)

<p>I am floatformat filters: {{123.456 | floatformat}} or {{123.456 | floatformat: 2}}</p>
Copy the code

Length (get length)

Get the length (which can be seen as the number of iterations of an iterable), in the same way len() in Python works

<! -- nickname =' search ', list =['one', '2', '3 ']-->
<p>I am a length filters: nickname - {{nickname | length}} | list - {{list | length}}</p>
Copy the code

Lower (cast to be careful) and upper(cast to uppercase)

Removes all strings specified in the value, similar to reqlace(args, ‘) in Python.

<! --' case conversion ': "AaBb"-->
<p>I am the lower and upper filter: mandatory lowercase - {{case conversion | lower}} | mandatory caps - {{case conversion | upper}}</p>
Copy the code

Safe (Marking the security string)

By default, Django escapes the passed value to protect against SQL injection attacks, and if the passed character is marked as a safe string, Django won’t escape it again.

<! -- 'js script' : '< script > alert (document. Domain) < / script >' - >
<p>I am safe filter: this script is {{js script}}, refresh the page while perform {{| js script safe}}</p>
Copy the code

Striptags (Delete tags)

Removes HTML tags from values

<! -- 'js script' : '< script > alert (document. Domain) < / script >' - >
<p>I am the striptags filter: {{| js script striptags}}</p>
Copy the code

Truncatechars (specified length)

If the specified length is exceeded, the character is replaced by an ellipsis (for example, if the string length is 5 or greater, the fifth character is replaced by an ellipsis, and subsequent characters are omitted).

<! -- 'js script' : '< script > alert (document. Domain) < / script >' - >
<p>I am truncatechars filters: {{| js script truncatechars: 10}}</p>
Copy the code

Template to optimize

The introduction of the template

A header and footer of the site, in order to avoid repetitive import, we can write a template that can be introduced in other pages, so that you can avoid repeating writing lots of code at the same time, also enhanced the maintainability of the code, inherited, if there is need to use {% include ‘HTML pages’ %} to the introduction of the parent class. {% include ‘HTML page ‘with parameter name =’ parameter’ %}

<! DOCTYPEhtml>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>I'm a test page</title>
</head>
<body>
    {% include 'header.html' %}
    <p>I really am a test page, don't come</p>{% include 'footer.html' with nickname ='xunmi' %}<! -- footer. The HTML code for: < p > I'm tail footer. The HTML file {{nickname}} < / p > -- >   
</body>
</html>
Copy the code

Inherited template

Inheritance is used for much the same purpose as the above reference, to reduce code duplication, but inheritance is more useful than import. Inheritance in a template is similar to Python inheritance in that the parent template defines some code that the child template needs, and the child template inherits

How to use the parent template

In HTML, you can reserve <% block padding name %> <% endblock %> to mark the area to be filled in the subtemplate. Such as:

<! DOCTYPEhtml>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Parent template page</title>
</head>
<body>
    <h1>I'm the parent template</h1>{% block fill 1 %}<p>The code here is overwritten by default</p>
    {% endblock %}
    <h2>At the top is the first child template</h2>{% block fill 2 %}<p>The code here is overwritten by default</p>
    {% endblock %}
    <h3>Above is the second subtemplate fill area</h3>
</body>
</html>
Copy the code

How to use a subtemplate

To import a child template to a parent template, use {% extends’ parent template name. HTML ‘%}. After importing the parent template, use the same <% block fill name %> <% endBlock %> method to fill the content in the reserved location in the parent template (the content will overwrite the content in the parent template block area, you can use {{block.super }} method is placed in the padding area to prevent overwriting), the padding name can be written in the block as well as in the endBlock, which can improve the readability of the code in large projects. Such as:

{% extends' inheritor. HTML '%} {% block fills a %}<p>I am in the fill area of the parent template</p>{% endBlock %} {% block fill two %} {{block.super}}<p>I got the area to fill the contents of area 2</p>{% endblock fill 2 %}Copy the code

Importing static files

In addition to HTML, some static files, such as CSS, JS, images, etc. are also indispensable in a website. We can write absolute or relative paths for today’s files, but this approach is not wise, if a static file is introduced several times, it will cause a huge amount of work in subsequent changes, and there may be missed changes.

Settings. py file Settings

The following Settings are done under settings.py:

  1. Determine whether or notINSTALLED_APPSInstalled in the'django.contrib.staticfiles',(Older Versions of Django are installed by default.)
  2. Make sure you specifySTATIC_URL = '/static/'(Static is the folder name, which can be customized, and is set at the bottom of settings.py. Django also defaults to this setting in older versions.)

    With the above two, we can normally use static files, but it will be more troublesome in the use process, we can optimize in the next few operations:
  3. The current Settings we can only use in the APP directorystaticSome static files are public, and we might want to put them in the root directory. In this case, we need to write them manually (we recommend placing them at the bottom of settings.py after STATIC_URL = ‘/static/’)
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')]Copy the code
  1. By default, every time we use a static file in HTML, we need to write to the HTML{% load static %}Introduce static folders. It’s a little tricky, but it’s in SettingsTEMPLATESIn theOPTIONSAdd to property'builtins': ['django.templatetags.static'],



    The operation completes the above steps and we use{% static 'static file name' %}Can be imported into the file

The introduction of the sample

I now put an image and A CSS in the static folder of the APP and root of the project respectively (with the background color set to masculine).

<! DOCTYPE html> <html lang="zh">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="{% static 'css.css' %}">
</head>
<body>
    <img src={% PNG '%}" alt="" width="200">
</body>
</html>
Copy the code