I. Introduction view function
A 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.
Two, three, form in response to
1:HttpResponse()
2:render()
render(request, template_name[, context])
Combined with a given template with a given context dictionary and returns after a render target Httpresponse
parameter:
request: a request for an object that generates the response
template_name: the full name of the template you want to use, obtain the optional parameter
context: add a dictionary to the template context. If a value in the dictionary is callable, the view will be called before rendering the template.
# render内部原理 from django.template import Template,Context def test(request): tmp = Template("<h1>{{ user }}</h1>") con = Context({'user':'jason'}) res = tmp.render(con) print(res) return HttpResponse(res)
3: redirect (transfer to redirect a URL)
Three, JsonResponse
Returns a json format string in two ways to the distal end
method one:
import json data={'name':'lqz','age':18} data1=['lqz','egon'] return HttpResponse(json.dumps(data1))
Second way:
from django.http import JsonResponse data = {'name': 'lqz', 'age': 18} data1 = ['lqz', 'egon'] return JsonResponse(data) return JsonResponse(data1,safe=False)
Four, CBV and FBV
class base view 和 Function base view
from django.views Import View class AddPublish (View): DEF dispatch (Self, Request, * args, ** kwargs): Print (Request) Print (args) Print (kwargs) # can write something similar decorator, before and after add the code obj = Super (). dispatch (Request, * args, ** kwargs) return obj def get(self,request): return render(request,'index.html') def post(self,request): request return HttpResponse('post')
Fifth, simple file upload
Note, encytpe coded form form to upload the file specified as formdata
def uploadfile(request): if request.method == 'POST': # print(request.FILES) # print(request.FILES.get('myfile')) file_obj = request.FILES.get('myfile') Open with (file_obj.name, ' wb ' ) AS f: for Line in file_obj.chunks (): # or directly on the target file for loop Line in file_obj for f.write (Line) return HttpResponse ( " the OK! " ) return the render (Request, ' index.html ' )