Django template language -1: a complete data acquisition examples

A, Django form (form) Request:

    Open when the default is GET request to obtain the contents of form form.

    The point when submitting a POST request, form submission form.

    Get the form to write the contents of the above differences:

django.shortcuts Import HttpResponse from 
from django.shortcuts Import the render, redirect 

DEF the Login (Request): 
    # Request contains all information submitted by the user. 
    = ERROR_MSG '' 
    IF request.method == 'the POST': 
        user = request.POST.get ( 'user', None) // Get get method using 'user' key, if there is no user key assignment None 
        pwd = Request .POST.get ( 'pwd', None) // get the user and pwd method in single form is input object attribute name. 
        User == IF '123' and pwd == '123456': 
            return the redirect ( 'http://www.baidu.com') 
        the else: 
            ERROR_MSG = 'user name or password' 
    
    return the render (Request, 'the login.html ', {' error_msg ': error_msg })


Two, {{key}}

        {{}} Html file specified in the key, is transmitted through the dictionary views.py, html displayed in the client corresponding to the key value is typical.

        HTML

<span>{{error_msg}}<span>


Three, HTML data dictionary and read the list

        Dictionary: Use Code to read Reading key:. Dict_name.key

        List: Use the index reading, list_name.0.

        views.py

def show(request):
    dict_name = {'name':'樱', 'age':19, 'mail':'[email protected]', 'fav':['football', 'sing', 'cook']}
    return render(request,'home.html', dict_name)

        Dictionary HTML:

<p>{{dictname.name}}</p>            \\樱
<p>{{dictname.age}}</p>             \\19
<p>{{dictname.mail}}</p>            \\[email protected]

        HTML List

<p>{{list_name.0}}</p>            \\football
<p>{{list_name.1}}</p>            \\sing
<p>{{list_name.2}}</p>            \\cook


Four, HTML in the for loop:

        Use %%} {marker loop, and using {% endfor%} End statement cycle

{%for k, v in dict_name%}
    \\HTML内容
    <p>{{k}}:{{v}}</p>
{%endfor%}
//views.py
return render(request, 'index.html', {'list_name':['a','b','c']})

{%for i in list_name%}
    <p>{{i}}</p>        //a,b,c
{%endfor%}

Five, HTML if the cycle:

{% if Condition%}. 1 
    \\ the HTML content 
    <P> K {} {}: {{V}} </ P> 
{%}% elif Condition 2 
    ... 
{the else%%} 
    ... 
{% endfor %}


Six, views.py get html template incoming data

    Html method of data submitted there are many, generally uses two types: POST and GET

        1, POST method request: in general for modifying, updating data.

        2, GET method request: submit URL displayed in, for example: http: \\ localhost \ hw \ id = 1 & name = david, typically used to request data from the server?

        3、其它。put,delete,head,option....

        4, the data upload type, designated in the form Form -> enctype = 'multipart / form-data'

     views.py data acquisition method:

        1, POST.get ( 'name', 'Default'), the unique value acquisition element, and if not, a default value is assigned

        2, POST.getlist ( 'name', 'default values') for a list of multi-value elements, if not, assign default values

get_Data DEF (Request): 
    get_post = request.POST.get ( 'user_name') # Gets the value of the HTML element named user_name, <INPUT name = 'user_name'> 
    get_post = request.POST.get ( 'user_name', None) # user_name elements not found, returns None 
    get_list = request.POST.getlist ( 'Favor') # obtain checkbox, multiple values of an HTML 
    get_get = request.GET.get ( 'user_name') # supra 
    get_get = request.GET.get ( 'user_name', None) # supra 
    get_get = request.GET.getlist ( 'user_name')

        3, FILES.get ( 'name') , acquiring the object file uploaded, the default file name,
                obj.name uploaded file name,
                obj.chunks () iterator read data block, read all the data for loop , for r in obj.chunks ()

get_file DEF (Request): 
    obj = request.FILES.get ( 'file_obj') 
    f = Open (obj.name, 'wb +') # upload the file name naming. 
    for i in obj.chunks (): # iterative loop to read data chunks. 
        f.write (I) 
    f.close ()


Seven, views.py function returns the URL:

    1, render: HTML template path, the format: render (request, 'HTML template name', transfer dictionary)

    2, redirect: returns a full URL, the format: redirect ( 'http://www.baidu.com')

    3, HttpResponse: Returns the HTML string in the format: HttpResponse ( '<p> This is just one example of </ p>')

show_data DEF (Request): 
    V = 1234 
    Jump # station the 
    return render (request, 'index.html' , { "dict": v}) 
    outside the station # jump 
    return redirect ( 'http://www.baidu.com ') 
    # directly return an HTML string. 
    return HttpResponse ( '<p> WARNING! </ p>')



Upload file:

urls.py

Import django.conf.urls URL from 
from ADMIN django.contrib Import 
Import index.views 
the urlpatterns = [ 
    URL (R & lt 'ADMIN ^ /', admin.site.urls), 
    URL (R & lt 'MAINS $ ^', index.views. mains), # http: // ip / mians, jump to the function of the mains at the views.py index directory 
    ## url (r '', index.views.mains ), # http: // ip, jumping mains function under views.py in the index directory 
    url (r '^ mains / up $', index.views.rev_file) # r '^ $' ^ $ defined beginning of the end, otherwise, all containing the word addresses steering confusing 
]

index.html

    Use the {{}}, {%%} template language. Simultaneous uploads

<! DOCTYPE HTML> 
<HTML lang = "EN"> 
<head> 
    <Meta charset = "UTF-. 8"> 
    <title> the Title </ title> 
</ head> 
<body> 
<form Action = "up" the enctype = "multipart / form-Data" Method = "POST">   
 // Action, jump to the URL, action = "/ up" for the root directory + up; action = "up" represents the current URL up + 
             
 // the enctype, form file may be received form              
    <INPUT type = "text" name = "USER_NAME" placeholder = "... the Input your name" /> 
    <INPUT name = "up_file" type = "file" /> 
    // type = "file", data representative can upload files 
    <p> 
        In Category: 
        software <input type = "checkbox" value="技术" name="f_type">
        HTML<input type="checkbox" value="HTML" name="f_type">
        编程<input type="checkbox" value="编程" name="f_type">
    </p>
    //创建多选框 
    <INPUT type = "Submit" value = "submit"> 
</ form> 
{%} // if f_name% if use is determined whether upload files, file upload, display information 
<p> <span style = " font -style: italic "> {{u_name }} </ span>, Your file:! {{f_name}} Upload Successful </ p> 
Category: 
    {I% for use in the F_TYPE%} // for reading the selected file classification  
        {{}} I 
    {%} endfor%                     
{%}% the else // not uploaded file cue 
<P> <span> by You do not Upload file! </ span> </ P> 
{%} endif% 
</ body> 
</ HTML>

test/views.py

django.shortcuts the render Import from 
Import os 
# the Create your views here Wallpaper. 

DEF MAINS (Request): 
    # for the first time open the URL, enter index.html page 
    return the render (Request, 'index.html') 

DEF rev_file (Request): 
    # reception form form data submitted 
    f_name = '' 
    u_name = '' 
    the F_TYPE = '' 
    IF request.method == 'the POST': 
        f_obj = request.FILES.get ( 'up_file', None)             
        # Gets an object file, print (f_obj) is the file name, but the actual object, because fILES defined __repr__ or __str__ 
        IF f_obj: 
            # If you have uploaded files 
            f_name = f_obj.name 
            u_name = request.POST.get ( 'user_name', None) 
            the F_TYPE = request.POST.getlist ( 'the F_TYPE') # get checkbox or multiple data type of option options
            f = open (os.path.join ( 'upload ', f_name), 'wb +') # upload file manage.py same directory folder 
            for i in f_obj.chunks (): #chunks (), iterator, using for reading 
                f.write (I) 
            f.close () 

    return the render (Request, 'index.html', { 'f_name': f_name, 'u_name': u_name, 'the F_TYPE': the F_TYPE}) 
    # back index. html content, but the browser address changes, and will be content if the content of the statement appears



Guess you like

Origin blog.51cto.com/yishi/2435284