Acquaintance Django- front end without isolating (b)

Context Manager

Role: Each view will need to use the inside of the operation is a public thing, you can put your own context managers defined in the investigation, so do not repeat in a written views.py

The order of execution: each view will then request again after the request context manager

How to use the context manager: 

  1. First define a context manager: process_context.py
  2. Defined in the context manager in function, the function must have a parameter request is
  3. This function should return a dictionary (here an extra introduce a function locals (), locals current role is to function in all local variables into a dictionary. There are examples below)
  4. Function created here, where required under the settings.py TEMPLATES-> OPTIONS-> context_processors configuration, each function will need to configure.
# Context manager process_context.py 
from . Import Models 

DEF category_process (Request):
     Print ( ' category_process ..... ' ) 
    catagories = models.Category.objects.filter (is_delete = False)
     return { ' NAV ' :} catagories 

DEF site_process (Request): 
    site_name = ' Tata's blog ' 
    desc = ' today is Sunday, tomorrow is Monday ' 
    return about locals ()   # about locals current role is to function in all local variables into a dictionary. This line is equivalent to the following line 
    # return {'site_name': site_name,'desc':desc}


settings.py
TEMPLATES
= [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'user.process_context.category_process', # This configuration creates a function ' user.process_context.site_process ' ], }, }, ]

Template inheritance 

Different html file will have some common content, we can also put them pulled out into a separate html file, we call this is called template inheritance.

How to use template inheritance

  1. First create a base.html, for common content store
  2. base.html required by changes in the content tag block. Format is as follows (Note css and js sometimes also need to become so in base.html in general will be set aside css and js mouth)

            {% Block content%} change contents are intermediate {% endblock%} #content which is used to identify changes is variable, if it is replaced css to css

       3. Public content pulled out, the original html needs to specify which public the contents of the html inherit (this is inherited base.html).

           {% extends 'base.html' %}

        4. The original html also specify what the content of the variable is used {% block content%} is an intermediate variable content  {% endblock%}

 

 

Paging

Introducing django required carrying paging classes: from django.core.paginator import Paginator

Knowledge tab rear: 
from
django.core.paginator Import Paginator L = Range (1, 51 ) page_obj = Paginator (L, 10) # 10 a sub # page_obj = Paginator (Article.objects.all (), 2 ) # article table data from the database search, a two Print (List (page_obj.page (. 1 ))) Print (page_obj.page (. 1)) # fetch a page, the results show that this <page 1 of 2>, now represents the total number of pages in which page Print (list (page_obj.page (1))) # turn into a list will be able to fetch data demonstrate a certain page of the Print (page_obj.count) # total number Article Print (page_obj.num_pages) # total points how many pages Print (page_obj.page_range)# Range tab cur_page = page_obj.page (. 1) # currently in that a Print (cur_page.has_previous ()) # determines whether a previous, in that a first specified current # Print (cur_page.previous_page_number () ) take the previous paging number # Print (cur_page.has_next ()) # determines whether there is a next Print (cur_page.next_page_number ()) # fetch the next paging number Print (cur_page.has_other_pages ()) # Analyzing Are there other pages Print (cur_page.paginator) # equivalent page_obj
前端实现代码:
 {% if articles.has_other_pages %}
      <div class="pagelist">
          {% if articles.has_previous %}
          <a href="/index?page={{ articles.previous_page_number }}&limit=10"><b>上一页</b></a>&nbsp;&nbsp;
              {% endif %}

          {% for page_num in articles.paginator.page_range %}
          <a href="/index?page={{ page_num }}&limit=10" >{{ page_num }}</a>&nbsp;&nbsp;
          {% endfor %}

          {% if articles.has_next %}
          <a href="/index?page={{ articles.next_page_number }}&limit=10">下一页</a>

          {% endif %}
      </div>
      {% endif %}

 

Django rich management background

  • Django style landscaping management background
    1. First install pip install simpleui
    2. Then added at settings.py-> INSTALLED_APPS 'simpleui'
  • Django rich database management background of a page action items
Admin.py configuration file in the sub-items

from
django.contribImportADMIN #the Register your Models here Wallpaper. From.ImportModels #configured as follows Class class, can enrich the operation items of the page, the page corresponding to admin.site under the operator. also increase the class name in the register classArticleAdmin (admin.ModelAdmin): list_display= ['title','category','the create_time','UPDATE_TIME']#which fields are displayed search_fields = ['title']#Specifies the search field by which to write, do not write the foreign key field of list_filter = [ ' category ' , ' is_delete ' ] # which field screening according to list_per_page = 10 # per page display how many admin.site.register (models.Article, ArticleAdmin) # here increase ArticleAdmin

 

Front and rear ends are not separated from the process

urls.py inside matching url, url found inside the function corresponding to the function to read the contents of the data and html to render, render to find the corresponding html in templates, the find after reading the contents of the html page is mapped to

Separate front and rear ends

Cross-domain issue: Install pip install django-cors-headers after allowing cross-domain

 

There are too many articles to display content will be cut by .... show how it does it need?

  1. Custom tag label

          Templatetags created under a subproject folder (Note: The folder name must be fixed call templatetags, there must be a folder __init__.py files), to build a my_tag.py files templatetags folder where custom we need to function, the front end can be called directly (Note: register variable name my_tag.py is fixed immutable)

my_tag.py 

from Django Import Template 

Register = template.Library () # Register fixed variable name can not be changed 

@ register.filter # filter up to two parameters, first of all {% load my_tag%} using the front end, with the second in local plus | + function name, if it is required to use two parameters: as article.desc {{| Test: 10}} 
DEF ABC (S, length = 10): # Analyzing string truncated to just more than 10. display .. 
    IF len (S)> length: 
        S = S [:. 11] + ' ..... ' 
    return S 


@ register.simple_tag # the simple_tag not limit parameter, if this parameter with many 
DEF ABC2 (S, length = 10 ):
     IF len (S)> length: 
        S= s[:11]+'....'
    return s

2. Call function in our custom front end

Step: We call a function from my_tag defined in the corresponding html 
{ % Load% my_tag } 

Step: In a specific reference the content at 

a first custom filter up to two parameters 
use a parameter
 <p> {{article.desc | abc}} < / p>   
use of two parameters
 <p> {{article.desc | abc : 10}} </ p>  

the second custom simple_tag usage parameter does not limit the number of pass
 < p> {% abc2 article.desc 10% } </ p>

 

Django comes filter

{% load my_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="/static/style.css" rel="stylesheet">
</head>
<body>
    欢迎《{{name}}》登录,今天是 === {{time}} ===

    {{ stus.0 }}
    <br>
    {{ stus |length  }}
    <br>
    {{ stus |slice:"0:2"  }}
    <br>
    {{ stus |join:"-"  }}
    <br>
    {{ name |default:"admin"  }}
    <br>
    {{ cur_time |date:"Y-m-d H:i:s"  }}
    <br>
    {{ h1_str |safe  }}
{#    #xss注入,加safe表示安全#}
    <br>
    {{ h1_str   }}
    <br>
    {{ words | truncatechars:20   }}
    <br>
    {{ age | add:2   }}
    <br>
    {{ name | add:"先生"   }}
    <br>
    {{ english_name | upper   }}
    <br>
    {{ english_name | lower   }}
    <br>
    {{ article_content|mingan }}
    <br>
    {{ article_content|mingan2:"金正恩" }}
    <br>
    {% mingan3 say "213" "sb" "傻x" %}

{#    <ul>#}
{#        {% for stu in stus %}#}
{#        <li>{{stu}}</li>#}
{#        {% endfor%}#}
{#    </ul>#}
</body>
</html>

Ok···

Guess you like

Origin www.cnblogs.com/tata-learning/p/12154415.html