Django Auxiliary technology Summary [static files, middleware, upload pictures, pagination case]

Source: Internet
Author: User

Static file settings static file Overview:

CSS files used in Web pages , JS files and pictures are called static files.

Setup process:
    1. Create a static folder in the project directory
    2. Create the Js,css,img folder in the created folder separately
    3. Make the following configuration in the setting.py file
Staticfiles_dirs = [Os.path.join (base_dir, ' static ')]  # Sets the physical address of the static file
    1. Set the static file path
Static_url = '/abc/'  # and the physical directory is the corresponding relationship, the logical concept
Methods of dynamically acquiring Static_url
    • To load a path in a template file
{% load staticfiles%}
    • The address of the picture is written

# These two effects are the same
    • Eventually rendered in the browser:
Dynamically get Static_url address <br>

Summary :

    • /abc/img/mm.jpg hides the directory where the server-side actually saves files
    • When static_url = '/abc/' This path is set to/abc/when the picture is loaded, it will go to the physical address Staticfiles_dirs set the project to find, the path of the lookup starts from the IMG folder
Middleware

Click to view middleware in detail: http://www.crazyant.net/1001.html

Get the IP address of the Access browser:

Request. meta[' REMOTE_ADDR ']

Role: Restricts browser user access to the server based on specified IP

Custom middleware Classes
    1. Create middleware.py in the app's directory
    2. Create middleware functions in this file--class
    3. Configure the middleware middleware_classes inside the setting.py to add
Function Call Order Description:
    • __INIT__--Service start accepts the first URL request call
    • Process_request--Generate Request object, URL match before calling
    • After the Prosess_view--url matches, the view function is called before the
    • Prosess_response---Call after the view function call is complete and the content is returned to the browser before calling
    • Prosess_exception-Called when an exception occurs inside a view function

Attention

Call Order: When there are multiple exception classes, they are all called, and the order of invocation is the opposite of the registration order

classblockedipmiddleware ():"""to create a class that blocks middleware"""    defProcess_view (self, request, Func_view, *view_args, * *View_kwargs):"""is called before the function call after the URL configuration ."""Addr= Request. meta['REMOTE_ADDR']        ifAddr = ='127.0.0.1':            returnHttpResponse ('Middleware block!!!')
block IP Case Code
classtestmiddleware ():"""creating a middleware class for testing"""    def __init__(self):Print('----init----')    defprocess_request (self, request):Print('----process_request----')        #return HttpResponse ('--process_request--')    defProcess_view (self, request, View_func, *view_args, * *View_kwargs):Print('----Process_view----')        #return HttpResponse ('--process_view--')    defProcess_response (self, request, response):Print('----process_response----')        #return HttpResponse ('--process_response--hello--kay--')        returnResponse#If the HttpResponse object is returned in the process of executing the middleware, it will call        #process_response () This function        #whenever a Httpresponsedui object is returned, it is called
Middleware Function Code
class Exceptiontestmiddleware (object):     """ Exception Middleware Class """    def process_exception (self, request, exception):         Print ('----exception_1----')         Print (Exception)     # The parameter exception returns an exception object
exception middle class codeUpload photo configuration upload picture process:
    • Make the following configuration in setting.py:
Media_root=os.path.join (Base_dir, "Static/media")
    • Create a media folder under the static path
    • Create a Booktest folder under the Media folder you created to save photos uploaded from views in the Booktest app
    • To create a model class that contains pictures
Class Pictest (models. Model): "" "    Create the Mode class" "That uploads the picture" "    gpic = models. ImageField (upload_to= ' booktest ')  # Specify the path to upload pictures

 

 fromDjango.confImportSettingsdefupload_action (Request):"""functions for uploading pictures"""    #1. Accept the uploaded filepic = Request. Files.get ('pic')    #print (pic.chunks)    #2. Path of stitching SaveSave_path ="%s/booktest/%s"%(settings. Media_root, Pic.name)#3. Open File    #save_file = open (Save_path, ' WB ')    #save_file.close ()    #4. Quick MethodWith open (Save_path,'WB') as Sava_file:#5. The content passed in is chunked, so you have to traverse the write         forFileinchpic.chunks ():#6. Write Datasava_file.write (file)#Save to databasep =pictest () p.gpic='booktest/%s'%pic.name p.save ()returnHttpResponse ('OK')
Upload a picture view in code
<form action= "/upload_action/" method= "post" enctype= "Multipart/form-data" >    {% csrf_token%}     <input type= "file" name= "pic" >    <input type= "Submit" value= "Upload" ></form>
upload a photo template in code
def use_pic (Request):     """ use a local picture    of the database 1. Find the path of the photo corresponding to the image from the data    2. Return to HTTP page    3. Load     "    " "in http page = PicTest.objects.get (id=1)    print(pic_path.gpic)    return ' booktest/use_pic.html ', {"pic_path": Pic_path.gpic})
using the code in the uploaded photos view
use the code in the uploaded photo templatePage out

Django provides classes for data paging, which are defined in django/core/paginator.py. The Paginator object is used to perform a paging operation on a column of n data. The object page is used to represent the data on page m.

Paginator Object
    • Method init (list, int): Returns the paging object, the parameter is the list data, the number of bars per polygon.
    • Property Count: Returns the total number of objects.
    • Property Num_pages: Returns the total number of pages.
    • Property Page_range: Returns a list of page numbers, starting with 1, for example [1, 2, 3, 4].
    • Method page (M): Returns the Page object that represents the data for page m, with the subscript starting at 1.
Page Object
    • Calling the page () method of the Paginator object returns the Page object without the need for manual construction.
    • Property object_list: Returns a list of the current page objects.
    • Property Number: Returns the current page, starting at 1.
    • Property Paginator: The Paginator object that corresponds to the current page.
    • Method Has_next (): Returns True if there is a next page.
    • Method Has_previous (): Returns True if there is a previous page.
    • Method Len (): Returns the number of current page objects.
    • Iterate Page objects: Access each object in the current page.
defShow_prov (Request, index):"""Show all provincial area 1. Create a Paged object 2. Gets the contents of the first Page 3. Gets all page number content displayed on the HTML page 4. Process Click to update the displayed content"""areas= AreaInfo.objects.filter (aparent__isnull=True)#areas pagination content every 10 pages create a paginated objectPaginator = paginator (areas, 10)    #How many page numbers are there in total?Page_list =Paginator.page_range#get the contents of the first page    #determine if the URL is Show_prov and the number is empty so make a judgment if it is empty, the first page is displayed.    if  notIndex:index= 1page=paginator.page (Index)#The next page of the number of children    #Pass the page number of the next page to the templatenext_index = Int (index) + 1#to pass the page number of the previous page to a templateprevious_index = Int (index)-1returnRender (Request,'booktest/page_test.html', {'page': page,'page_list': Page_list,"Next_index": Next_index,'Previous_index': Previous_index})
code in Paging view
<body><ul>    {% forAreainchPage%}        <li>{{area.atitle}}</li> {% ENDFOR%}</ul>{# Returns True #}{if there is a next page%ifPage.has_previous%}    <a href= "/show_prov{{Previous_index}" > previous </a>{% endif%}{% forPage_indexinchPage_list%}    {% Comment%} Page.number Returns the current number of pages according to page to determine if there is another page/previous page option {% endcomment%}    {%ifPage_index = = Page.number%} {{Page_index}} {%Else%}        <a href= "/show_prov{{Page_index}}" >{{page_index}}</a> {% ENDIF%}{% ENDFOR%}{# True if there is a next page #}{%ifPage.has_next%}    <a href= "/show_prov{{next_index}" > next </a>{% endif%}</body>
code in the paging template
# location parameter optional URL (r'^show_prov (\d*)/$', Views.show_prov)
Paging URL Configuration code

Django Auxiliary technology Summary [static files, middleware, upload pictures, pagination case]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.