Django Template Language-1: A complete data acquisition example

Posted by cavolks on Tue, 03 Sep 2019 19:16:37 +0200

1. Django form request:

The default when opening is a GET request to get the contents of the form.

Point submission occurs when a POST request submits the contents of the form.

Write the Get Form Content based on the above differences:

from django.shortcuts import HttpResponse
from django.shortcuts import render, redirect

def login(request):
    #request contains all information submitted by the user.
    error_msg = ''
    if request.method == 'POST':
        user = request.POST.get('user', None)        //Get the'user'key using the get method and assign None if there is no user key
        pwd = request.POST.get('pwd', None)          //The user and pwd in the get method are the name properties of the input object in the form form.
        if user == '123' and pwd == '123456':
            return redirect('http://www.baidu.com')
        else:
            error_msg = 'ERROR Incorrect username or password'
    
    return render(request, 'login.html', {'error_msg':error_msg})


2. {{key}}

{{}} specifies the key in the html file, passes the dictionary through views.py, and html displays the key value corresponding to the dictionary on the client.

        HTML

<span>{{error_msg}}<span>


3. HTML Read Dictionary Data and Lists

Dictionary: Use. to read dictionary key: dict_name.key

List: Read with. Index, list_name.0

        views.py

def show(request):
    dict_name = {'name':'Cherry', 'age':19, 'mail':'ying@126.com', 'fav':['football', 'sing', 'cook']}
    return render(request,'home.html', dict_name)

Dictionary HTML:

<p>{{dictname.name}}</p>            \\Cherry
<p>{{dictname.age}}</p>             \\19
<p>{{dictname.mail}}</p>            \\ying@126.com

List HTML

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


4. for loop in HTML:

Mark the loop statement with {%%} and declare the end of the loop with {%endfor%}

{%for k, v in dict_name%}
    \\HTML content
    <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%}

5. if loop in HTML:

{%if Condition 1 %}
    \\HTML content
    <p>{{k}}:{{v}}</p>
{%elif Condition 2%}
    ...
{%else%}
    ...
{%endfor%}


6. View.py Obtain data from html template

There are many ways to submit data from html, typically using two types: POST and GET

1. POST method request: generally used to modify and update data.

2. GET Method Request: Submit as a web address display, for example: http:\localhost\hw\?Id=1&name=david, which is commonly used to request data from a server

3. Other.put,delete,head,option....

4. Upload data of file type, specify in Form form -->enctype='multipart/form-data'

View.py Get Data Method:

1, POST.get('name','default'), get the unique value of the element, and if not, assign the default value

2. POST.getlist('name','default'), get a list of multivalued elements, if not, assign default values

def get_data(request):
    get_post = request.POST.get('user_name')             #Get the value of the HTML element named user_name, <input name='user_name'>
    get_post = request.POST.get('user_name',None)        #No user_name element found, returning None
    get_list = request.POST.getlist('favor')                       #Get the HTML value of checkbox, multiple
    get_get = request.GET.get('user_name')             #Same as above
    get_get = request.GET.get('user_name',None)        #Same as above
    get_get = request.GET.getlist('user_name')

3. FILES.get('name'), get the uploaded file object and display the file name by default.
obj.name displays the uploaded file name.
The obj.chunks() iterator reads data blocks, uses the for loop to read all data, and for r in obj.chunks()

def get_file(request):
    obj = request.FILES.get('file_obj')
    f = open(obj.name, 'wb+')        #Name the uploaded file name.
    for i in obj.chunks():           #Loop through chunks iterator data.
        f.write(i)
    f.close()


7. View.py function returns web address:

1. render: HTML template path, format: render(request,'HTML template name', passed dictionary)

2. redirect: Returns a complete URL in the format redirect('http://www.baidu.com')

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

def show_data(request):
    v=1234
    #Intra-Station Jump
    return render(request,'index.html',{"dict":v})
    #Out-of-Station Jump
    return redirect('http://www.baidu.com')
    #Returns the HTML string directly.
    return HttpResponse('<p>Warning!</p>')



Example upload file:

urls.py

from django.conf.urls import url
from django.contrib import admin
import index.views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url( r'^mains$',index.views.mains),            #http://ip/mians, jump to mains function under views.py in index directory
    ## url( r'',index.views.mains),                        #http://ip, jump to the mains function under views.py in the index directory
    url(r'^mains/up$', index.views.rev_file)       #r'^ $'Definition ^ Start $End, otherwise all addresses containing this word will be turned around and confused easily
]

index.html

{{}, {%}, template language used.Simultaneous upload

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="up" enctype="multipart/form-data" method="post">  
 //Action, jump to the web address, action="/up" for the root directory+up; action="up" for the current web address+up
             
 //enctype, form form receives files
    <input type="text" name="user_name" placeholder="Input your name..." />
    <input name="up_file" type="file"/>
    //type="file", which means you can upload file-type data
    <p>
        File classification:
        Software<input type="checkbox" value="technology" name="f_type">
        HTML<input type="checkbox" value="HTML" name="f_type">
        programming<input type="checkbox" value="programming" name="f_type">
    </p>
    //Create multiple check boxes
    <input type="submit" value="Submit">
</form>
{% if f_name %}        //Use if to determine whether to upload a file, upload a file, and display information
<p><span style="font-style: italic">{{ u_name }}</span>,Your file:{{ f_name }} Upload Successful!</p>
Classification:
    {% for i in f_type %}            //Use for reading selected file classifications
        {{ i }}
    {% endfor %}                    
{% else %}                           //Not uploaded file prompt
<p><span>You don't upload file!</span></p>
{% endif %}
</body>
</html>

test/views.py

from django.shortcuts import render
import os
# Create your views here.

def mains(request):
    #Open the web address for the first time, enter the index.html page
    return render(request, 'index.html')

def rev_file(request):
    #Receive data submitted by form form
    f_name = ''
    u_name = ''
    f_type = ''
    if request.method == 'POST':
        f_obj = request.FILES.get('up_file', None)            
        #Get the file object, print (f_obj) is the file name, but it is the object because FILES defines u repr_ or u str_u
        if f_obj:
            #If there are uploaded files
            f_name = f_obj.name
            u_name = request.POST.get('user_name', None)
            f_type = request.POST.getlist('f_type')            #Get data for option options of type checkbox or multiple
            f = open(os.path.join('upload', f_name), 'wb+')    #upload folder of management.py sibling directory
            for i in f_obj.chunks():                           #chunks(), iterator, read with for
                f.write(i)
            f.close()

    return render(request, 'index.html', {'f_name': f_name, 'u_name': u_name, 'f_type': f_type})
    #Return the content of index.html, but the web address of the browser changes and the content of the if statement appears



Topics: Python Django Programming