This article brings you a detailed explanation of Django views in python (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
A view function (class), referred to as view, is a simple Python function (class) that contains business logic. It accepts Web requests and returns Web responses.
The response can be the HTML content of a web page, a redirect, a 404 error, an XML document, or an image.
Response must be returned no matter what logic the view itself contains. It doesn't matter where the code is written, as long as it is in your current project directory. Nothing more is required - "nothing magical" so to speak.
In order to put the code somewhere, it is a common convention to place the views in a file named views.py in the project or application directory.
Example: A view that returns the current date and time in the form of an html document:
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 explain the above code line by line:
First, we start with The django.http module imports the HttpResponse class and Python’s datetime library.
Next, we define the current_datetime function. It is the view function. Each view function takes an HttpRequest object as the first parameter, and is usually called request.
Note that the name of the view function is not important; it does not need to be named in a consistent way for Django to recognize it. We named it current_datetime because this name can more accurately reflect the functions it implements.
This view will return an HttpResponse object containing the generated response. Each view function is responsible for returning an HttpResponse object.
Django uses request and response objects to pass state through the system.
When the browser requests a page from the server, Django creates an HttpRequest object, which contains metadata about the request. Django then loads the corresponding view, passing this HttpRequest object as the first parameter to the view function.
Each view is responsible for returning an HttpResponse object.
CBV (class based view) and FBV (function based view)
The function-based view is called FBV, and the view can also be written as class-based.
FBV version
# FBV版添加班级 以函数的方式实现 def add_class(request): if request.method == "POST": class_name = request.POST.get("class_name") models.Classes.objects.create(name=class_name) return redirect("/class_list/") return render(request, "add_class.html")
CBV version
# CBV版添加班级 以类的方式实现 from django.views import View class AddClass(View): # 继承View中的所有属性 def get(self, request): # 如果是get请求,就执行此段函数 return render(request, "add_class.html") def post(self, request): # 如果是post,请求就执行此段函数 class_name = request.POST.get("class_name") models.Classes.objects.create(name=class_name) return redirect("/class_list/")
Note: When CBV is used, corresponding modifications must be made in urls.py:
# urls.py中,要加括号 url(r'^add_class/$', views.AddClass.as_view()), # 注意: Addclass中并没有定义as_view方法,而是继承view中的方法,从而使其按照 #相应条件执行相应程序. 流程 1. AddPress.as_view() —— 》 view函数 2. 当请求到来的时候执行view函数: 1. 实例化自己写的类 —— 》self self = cls(**initkwargs) 2. self.request = request 3. 执行 self.dispatch(request, *args, **kwargs) 1. 执行父类中的dispatch方法 1. 判断请求方式是否被允许 1. 允许的情况 handler = 通过反射获取 get post 方法(指的是自己定义的类中的方法) 2. 不允许的情况 handler = 不允许的方法 3. handler(request, *args, **kwargs) 2. 返回HttpResponse对象 4. 返回HttpResponse对象 给django
By inheriting the view method, it helps to complete the logical business The functions (eight receiving methods such as post, get, filter, etc.) are more concise than FBV
CBV version does not require if judgment and is more modular.
CBV version adds decorator
Methods in a class are not exactly the same as independent functions, so function decorators cannot be applied directly to methods in a class, we need to convert them into method decorators first.
Django provides the method_decorator decorator to convert function decorators into method decorators.
Method 1:
# Be careful when using CBV, request After coming over, the dispatch() method will be executed first. If we need to perform some operations on specific request processing methods in batches, such as get, post, etc., we can manually rewrite the dispatch method here. This dispatch method is the same as adding decoration on FBV. The effect of the device is the same.
##Method 2:
When a page is requested, Django will create an HttpRequest object containing the original information of the request.
Django will automatically pass this object to the corresponding view function. Generally, the view function conventionally uses the request parameter to receive this object.
Common values related to requests
path_info Returns the user access url, excluding the domain name
method The string representation of the HTTP method used in the request, expressed in all uppercase letters.
GET A dictionary-like object containing all HTTP GET parameters
POST A dictionary-like object containing all HTTP POST parameters
body The request body, the byte type request.POST data is
Attributes extracted from body
All attributes should be considered read-only unless otherwise stated.
Attributes:
Django encapsulates the request line, header information, and content body in the request message into attributes in the HttpRequest class.
Except for special instructions, everything else is read-only.
0.HttpRequest.scheme
A string representing the request scheme (usually http or https)
1. HttpRequest.body
A string , represents the body of the request message. It is very useful when processing non-HTTP messages, such as binary images, XML, Json, etc.
However, if you want to process form data, it is recommended to use HttpRequest.POST.
In addition, we can also use python's class file method to operate it. For details, refer to HttpRequest.read().
2. HttpRequest.path
A string representing the path component of the request (excluding domain name).
For example: "/music/bands/the_beatles/"
3. HttpRequest.method
A string indicating the HTTP method used in the request. Capital letters must be used.
For example: "GET", "POST"
4, HttpRequest.encoding
A string indicating the encoding method of the submitted data (if it is None, it means using DEFAULT_CHARSET setting, default is 'utf-8').
This attribute is writable and you can modify it to modify the encoding used to access form data.
Any subsequent access to the property (such as reading data from GET or POST) will use the new encoding value.
If you know the encoding of the form data is not DEFAULT_CHARSET, use it.
5. HttpRequest.GET
A dictionary-like object containing all parameters of HTTP GET. Please refer to the QueryDict object for details.
6. HttpRequest.POST
A dictionary-like object. If the request contains form data, the data will be encapsulated into a QueryDict object.
POST requests can have an empty POST dictionary - if a form is sent via the HTTP POST method, but there is no data in the form, the QueryDict object will still be created.
Therefore, you should not use if request.POST to check whether the POST method is used; you should use if request.method == "POST"
In addition: If you use POST to upload If it is a file, the file information will be included in the FILES attribute.
7. HttpRequest.COOKIES
A standard Python dictionary containing all cookies. Both keys and values are strings.
8. HttpRequest.FILES
A dictionary-like object that contains all uploaded file information.
Each key in FILES is the name in , and the value is the corresponding data.
Note that FILES will only contain data if the request method is POST and the submitted