Django-- view basis

1. view function

View function, referred to as a view, essentially a simple Python function that accepts a response back to the Web and Web requests.

Content of the response can be HTML pages, redirect, a 404 error, XML documents, such as images or anything. However, no matter what the view itself is the processing logic, preferably return a type of response.

Written in code view function does not matter where, as long as it is below your Python directory. But usually we agreed to place the view in a project or application files in the directory named in views.py.

1.1 Example

from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)

Let us analyze the above code line by line:

  • First, the django.httpmodule is introduced HttpResponseclass, and the Python datetime library.
  • Then, we define the current_datetimeview function.
  • Each view function takes an HttpRequest object as the first position parameter, named general request, you can call it anything, but it does not meet the rule, it is best not to do so.
  • The name of the view function does not enforce the rules, but try not to, and Django Python and a variety of built-in name the same name, and try to accurately reflect its function, such as here current_datetime.
  • The view returns an HttpResponse object containing the generated HTML page.
  • Common render, redirect, is an HttpResponse HttpResponse object returned.

 1.2 Classification trying coding

 Divided into two types: FBV (create a view function) and CBV (create a view class)

 1.2.1 FBV (business logic written in a function)

# views.py
1 from  django.shortcuts import  render,Httpresponse,redirect
2 from app_name import models
3 
4 def add_class(request):
5     if  request.method =='POST':
6             class_name = request.POST.get('class_name')
7             models.Classes.objects.create(name=class_name)
8             return  redirect('/class_list/')
9     return render(request,'add_class.html')


# urls.py
1 from app_name from views

2 urlpatterns = [
3  path('addclass/',views.add_class),]
View Code

1.2.1 CBV (written in the business logic class)

# views.py
from django.views import View
from app_name import models

class AddClass(View):        # 必须继承类View

    def get(self, request):
        return render(request, 'add_class.html')

    def post(self, request):
        class_name = request.POST.get('class_name')
        models.Class.objects.create(name=class_name)
        return redirect('/class_list/')


# Use CBV, urls.py also need to make the corresponding changes 
# the urls.py 
path ( ' add_class / ' , views.AddClass.as_view ()),
View Code

 CBV process:

1, views.AddClass.as_view () -> Returns view function object
 2 , the incoming request when the view function is executed
     2.1 , instantiates the AddClass, assigned to Self 
        self.request = Request
     2.2 , self.dispatch method executed (if the AddClass , their execution is not performed, then the View)
         2.2.1 , if the request is legitimate 
            valid: 
                Handler = getattr (Self, request.method.lower (), self.http_method_not_allowed) 
            invalid: 
                get a http_method_not_allowed method, error
         2.2 .2 , acquired method of performing a method corresponding to the type defined in the class, get (request,) or POST (Request,)
         2.2.3 , to give the object httpResponse, returned to self.dispatch
         2.2.4, to give the object httpResponse returned to the django processing
View Code

 

2.HttpRequest objects

Whenever a request is sent from a user, Django the HTTP packet content, packaged into a HttpRequest object, and pass it to each view position as a function of a first parameter, i.e. request, we call for.

Common values ​​related requests

  • path_info    return url user access, does not contain the domain name, not only the path parameters / index /
  • path Ibid.
  • get_full_path () returns the full path, excluding the domain name / midd / index /? wd = 333 & key = 3333
  • The method of HTTP request method string representation used in, all uppercase represents
  • GET dictionary-like object containing all HTTP GET parameters
  • Dictionary-like object containing all POST HTTP POST parameters
  • request body member, request.POST data type byte is extracted from inside the body to
  • FILES upload files, add {} Note form tag enctype = "multipart / form-data" attribute
  • HTTP_REFERER Jump to page last visited the page before the user is not logged in to access, log on to jump to that page, redirect (request.Meta.get ( 'HTTP_REFERER', '')

2.1HttpRequest property

/ * 

1 .HttpRequest.GET 
  an object similar to a dictionary that contains all the parameters of HTTP GET. Please refer to QueryDict object. 

2 .HttpRequest.POST 
  objects like a dictionary, if the request is included in the form data, the data will be packaged into QueryDict objects. 
  POST requests can with an empty POST dictionary - if via HTTP POST method sends a form, but the form does not have any data, QueryDict objects will still be created. 
   Therefore, you should not use IF request.POST to check whether you are using the POST method; you should use IF request.method == " POST " 
  Also: If you use the POST uploaded file, the file information will be included in FILES property. 
     Note: a plurality of key-value pairs, when the input type such as checkbox, SELECT labels, with: 
        request.POST.getlist ( " Hobby " )

 . 3 .HttpRequest.body 
  a string representing the request packet main body. Very useful when dealing with non-HTTP form of messages, such as: binary images, XML, Json and so on.
  However, if the time to process the form data, recommend or use HttpRequest.POST. 

4.HttpRequest.path 
  a string that represents the path component (Domain) request. 
  For example: " / Music / bands Scrap / the_beatles / "
 
. 5 .HttpRequest.method 
  a string that represents an HTTP request method used. You must use uppercase. 
  For example: " the GET " , " the POST "
 
. 6 .HttpRequest.encoding 
  a string indicating a coding mode data submission (if the indication None DEFAULT_CHARSET set, the default is ' UTF-. 8 ' ). 
   This property is writable, you can modify it to modify the encoded form data access used. 
   Next, any access to the properties (e.g., reading data from the GET or POST) encoding will use the new values. 
   If you know the encoding is not DEFAULT_CHARSET form data, then use it. 

7 .HttpRequest.META
   A standard Python dictionary containing all the HTTP headers. Specific header information depends on the client and the server, the following are some examples: 
    CONTENT_LENGTH - the length of the body of the request (a string).
    MIME type text request - CONTENT_TYPE. 
    HTTP_ACCEPT - response may receive the Content . - the Type. 
    HTTP_ACCEPT_ENCODING - response may be received encoded. 
    HTTP_ACCEPT_LANGUAGE - response may be received language. 
    HTTP_HOST - HTTP Host header sent by customer. 
    HTTP_REFERER - Referring page. 
    HTTP_USER_AGENT - Client the User - Agent string. 
    QUERY_STRING - single string in the form of a query string (not parsed form). 
    REMOTE_ADDR - IP address of the client. 
    REMOTE_HOST - host name of the client. 
    REMOTE_USER - after user authentication server. 
    REQUEST_METHOD - A string, such as " GET " or " POST " 
    SERVER_NAME - host name of the server. 
    SERVER_PORT - server port (a string).
   When seen from the above, and in addition CONTENT_LENGTH CONTENT_TYPE, any HTTP request header is converted to META keys 
    are all capital letters and finally replaced with an underscore connector plus HTTP_ prefix. 
    So called X- - Bender converted into a head in the META HTTP_X_BENDER bond. 

8 .HttpRequest.FILES 
  an object similar to a dictionary that contains all the uploaded file information. 
   Each key is FILES <INPUT type = " File " name = "" /> The name, the value compared with the corresponding data. 
  Note that, FILES, and only for the POST method request submitted <form> = with the enctype " multipart / form-Data " in the case of only 
   contains data. Otherwise, FILES will be a blank dictionary-like object. 

9 .HttpRequest.COOKIES 
  a standard Python dictionary containing all of the cookie. And keys are string values. 

10.HttpRequest.session 
   a subject can read but also write a dictionary-like, represents the current session. Only available when Django enable support sessions. 
    Complete documentation for details see session. 

. 11 .HttpRequest.user (using the user authentication component) 
  object AUTH_USER_MODEL type, indicates the user currently logged on. 
  If the user is not currently logged in, user will be set to an instance of django.contrib.auth.models.AnonymousUser. You can () to distinguish them by is_authenticated. 

    For example: 
    IF request.user.is_authenticated ():
         # the Do something for logged-in the Users. 
    The else :
         # . Anonymous the Do something for the Users 
       the User only available if Django is enabled when AuthenticationMiddleware middleware.
     -------------------------------------------------- ----------------------------------- 
    anonymous user 
    class models.AnonymousUser
    django.contrib.auth.models.AnonymousUser django.contrib.auth.models.User class implements the interface, but offers several different points: 
    the above mentioned id is always None. 
    username is always an empty string. 
    get_username () always returns an empty string. 
    is_staff and is_superuser forever to False. 
    is_active forever to False. 
    groups and user_permissions forever empty. 
    is_anonymous () returns True instead of False. 
    is_authenticated () returns False instead of True. 
    set_password (), check_password (), save () and delete () caused NotImplementedError. 
    New in Django 1.8 : 
    New AnonymousUser.get_username () to better simulate django.contrib.auth.models.User. 

* /
View Code

 

2.2HttpRequest common method

. 1 .HttpRequest.get_host () 

  according to the HTTP_X_FORWARDED_HOST (if open USE_X_FORWARDED_HOST, default False) HTTP_HOST header information and returns the requested original host. 
   If the two headers do not provide the appropriate values, and then using SERVER_NAME SERVER_PORT, in the PEP 3333 detailed description. 

  USE_X_FORWARDED_HOST: A Boolean value that specifies whether to prioritize the use of the X- -Forwarded- header Host, only in the case of proxy settings of the header, can be used. 

  For example: " 127.0.0.1:8000 " 

  Note: When the host is located behind the plurality of agents, get_host () method will fail. Unless you use the header rewrite the middleware proxy. 

2 .HttpRequest.get_full_path () 

  return path, if you can add the query string. 

  For example: " / Music / bands Scrap / the_beatles / Print = to true? "

 
3 .HttpRequest.is_secure () 

  If the request is secure Returns True; that is, over HTTPS request is initiated through. 

 

4 .HttpRequest.is_ajax ()

  If the request is initiated by the XMLHttpRequest, it returns True, HTTP_X_REQUESTED_WITH by checking whether the respective header string ' XMLHttpRequest ' . 

  Most modern JavaScript libraries will be sent to this head. If you write your own XMLHttpRequest call (on the browser side), you must manually set this value to make is_ajax () can work. 

  If a response is needed based on whether the request is initiated by AJAX, and you are using some form of caching such as Django's cache middleware, 
   you should use vary_on_headers ( ' HTTP_X_REQUESTED_WITH ' your view) decorated to allow the response to be cached correctly.
View Code

Note: a plurality of key-value pairs, when the input type such as checkbox, SELECT labels, with:

request.POST.getlist("hobby")

 

3.HttpResponse objects

Compared with the HttpRequest object is created automatically by Django, HttpResponse objects are our terms of reference of. We write each view will need to be instantiated, fill and return an HttpResponse.

HttpResponse class located django.http module.

3.1HttpResponse()

Direct pass strings

from django.http import HttpResponse
response = HttpResponse("Here's the text of the Web page.")

 

Set or delete header information

response = HttpResponse()
response['Content-Type'] = 'text/html; charset=UTF-8'
del response['Content-Type']

 

3.2 render()

Combined with a given template with a given context dictionary and returns an HttpResponse object after rendering.

parameter:

  • request: a request for an object that generates the response.
  • Parameters to use the full name of the template, optional: template_name
  • context: add a dictionary to the template context. The default is an empty dictionary. If a value in the dictionary is callable, the view will be called before rendering the template.
  • content_type: MIME type generated document to be used. The default value of DEFAULT_CONTENT_TYPE settings. The default is 'text / html'
  • status: status code of the response. The default is 200.
  • useing: The name of the template engine load the template.
from django.shortcuts Import the render 

DEF the my_view (Request):
     # Code view written here 
    return the render (Request, ' MyApp / index.html ' , { ' foo ' : ' bar ' })
View Code

 

3.3 redirect()

Reception parameters:

  • A view, may have parameters: using urlresolvers.reverse  to reverse resolve the name
  • An absolute or relative URL, will remain intact as the redirection location.

It returns a temporary default redirection; transfer permanent = True  can return a permanent redirection.

Pass the name of a view

def my_view(request):
    ...
    return redirect('some-view-name', foo='bar')

Transfer to redirect to a specific URL

def my_view(request):
    ...
    return redirect('/some/url/')

 

3.4 JsonResponse

JsonResponse is HttpResponse subclass, designed to generate a response JSON-encoded.

from django.http import JsonResponse

response = JsonResponse({'foo': 'bar'})
print(response.content)

b'{"foo": "bar"}'

The default can only pass a dictionary, a dictionary if you want to pass a non-keyword arguments need to set up safe.

response = JsonResponse([1, 2, 3], safe=False)

 

Guess you like

Origin www.cnblogs.com/lymlike/p/11563794.html