Django-- view views

1. What is a view?

  View function, referred to as a view, Python is a simple function that accepts a response back to the Web and Web requests. The response may be a page's HTML content, a redirect, a 404 error, an XML document, or a picture... Anything is possible. No matter what the view itself contains logic, it must return a response. Write the code where it does not matter, as long as it is in your Python directory. In addition there is no more requirement - and you can say, "There's nothing magical place." In order to put the code somewhere, will view the agreement is placed in the project or application directory named views.py file.

  As shown in FIG view function:

from django.shortcuts import render, HttpResponse, redirect

# Create your views here.

def index(request):
    import datetime
    now = datetime.datetime.now()
    ctime = now.strftime('%y-%m-%d,%X')
    return render(request, "index.html", {"ctime": ctime})

  As shown, index function is a function of view, his argument must have a request, you must return an HttpResponse object. The function name of the view function does not need unity, we can only express the function function.

2, HttpRequest request object

  Common methods:

  request.method: output request mode

  request.path: output path

  request.POST:POST request data

  request.GET: get the requested data

  request.META: request header

  request.get_full_path () to get the path parameter also takes

3, HttpResponse response object

  There are three main forms of response object:

  HttpResponse()

  render()

  redirect()

  HttpResponse is the string to add in parenthesis that require a response, said two other major here.

4、render()

  Binding template and a given context dictionary, returns after a HttpResponse object rendering.

  There are two functions: 1, read the file string

  

def index(request):
    
    return render(request, 'index.html'

  2, embedded variables

  code as shown in views:

DEF index (Request):      
    
    shangping_list = [ ' apple ' , ' banana ' , ' watermelon ' ] 
    name = ' QQQ ' 
    return the render (Request, " index.html " , { ' SP ' : shangping_list, ' name ' : name} )

  That is followed by the dictionary with a

  As shown in FIG template:

<body>
    用户:{{ name }}
    <h2>商品信息</h2>

<ul>

    {% for foo in sp %}
        <li>{{ foo }}</li>
    {% endfor %}

</ul>


</body>

  This can be through a dictionary of key data will pass up on the page. And a method of extraction elements in the sequence loop.

  Page is shown below:  

User: qqq 
product information 
apple 
banana 
watermelon

 

  

  

 

Guess you like

Origin www.cnblogs.com/490144243msq/p/11570092.html