This is the sixth day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Django views often use Http Response(), render(), and redirect() functions to respond to requests

The Http Response () function

Render () function

The Render () function, provided by the Django.Shortcuts module, generates and returns an Http Response object based on the template file and the dictionary-type variables passed to the template file.

The function format is

render(request, template_name, context=None,content_type=None, status=None)
Copy the code
  • Request: A position parameter that represents a Web request to a view function and encapsulates all the data in the request header, which is actually the view parameter request.

  • Template_name: Mandatory location parameter, which refers to the name of the template file to use, usually an HTML file in the templates directory.

  • Context: Optional. The data is a dictionary type. By default, it is an empty dictionary that holds variables to be passed to an HTML file.

  • Content_type: an optional named parameter that is used to set the MultipurposeInternet Mail Extension (MIME) type of the document being generated. DEFAULT_CONTENT_TYPE defaults to text/ HTML.

  • Status: Indicates the status code of the response. The default value is 200. This parameter is optional.

    Example:

    from django.shortcuts import renderdef test_view(request):
    The view code is written here
    def xxx(request) :
    	xxxxxxx
    	return render(request, 'index.html', {'welcome': 'hello world! '} ,content_type='text/html')
    
    # pass the welcome variable with the value 'Hello world! Variables'
    Copy the code

Redirect () function

The redirect() function takes an argument to redirect the browser to the specified URL. This parameter can be a data Model object, view function name, or URL.

When the parameter is a data Model object

The Redirect () function calls the get_absolute_url() function defined in the data model, takes the URL value returned by the function, and jumps to that URL.

example

Urls. Py:

. path('dep/<int:dep_id>/',views.depdetail,name='depdetail'),
path('test_redirect/',views.test_redirect),
....
Copy the code

models.py:

# Import data module
from django.db import models
# import the reverse parsing function
from django.urls import reverse
# Department data Model (Department data sheet)
class department(models.Model) :
    The department name is a character type
    dep_name=models.Char Field(max_length=32,verbose_name='Department Name',unique=True, blank=False)
    # Department remarks
    dep_script=models.Char Field(max_length=60,verbose_name='note',null=True)
    # get_absolute_URL () method for the data model
    def get_absolute_url(self) :
/dep/ self.pk /
		return reverse('depdetail',kwargs={'dep_id':self.pk})
# Define a function get_absolute_URL () in the data model department that returns a URL.
Copy the code

Reverse () is the URL reverse parsing function whose first argument is ‘depdetail’, which is the URL configuration item named depdetail. The reverse parsing process is: Find the configuration item named depdetail in the current test_view urls.py application. The reverse() function finds the corresponding URL, combines it with the dictionary type argument passed to it (kwargs={‘dep_id’:self.pk}), and eventually parses to produce the full URL.

views.py:

from django.shortcuts 
import render,Http Response,redirect
from . import models
def depdetail(request,dep_id) :
    Fetch a record based on the parameter value passed in
    obj=models.department.objects.get(id=dep_id)
    # return Http Response object
    return Http Response('Department:'+obj.dep_name+', note: '+obj.dep_script)
def test_redirect(request) :
    obj=models.department.objects.get(id=1)
    Redirect () = get_absolute_URL = get_absolute_URL
    # This URL corresponds to the view function views.depdetail(), which is actually called
    return redirect(obj)
Copy the code

The test_redirect() view function has a redirect() function. The redirect() function runs in three steps.

  • Because obj, the parameter passed to the Redirect () function, is a data model instance object (data record) whose data model class is Department, the get_Absolute_URL () method for this object is called.
  • Get_absolute_url () uses the reverse() function to parse the URL configuration item name and obj ID as parameters to return a URL that looks like “/dep/1/” to the redirect() function.
  • Once the reverse() function gets the URL, it looks for a match in urls.py, finds the corresponding view function as depdetail(), and executes the function.

If the argument is the view function name

The Redirect () function reverses the URL from the view function name and view function parameters and redirects it to that URL. The following code passes in a view function name, depdetail, and parameters

def test_redirect(request) :
The view function depdetail() takes the dep_id argument
	return redirect('depdetail',dep_id=2)
Copy the code

The redirect() function is performed by first reversely parsing the URL, finding the URL view function in urls.py, and executing the depdetail() view function. Externally, it is understood that the view function depdetail() is called directly from redirect().

Parameter is the full URL

The redirect() function opens the web page to which the URL points. Parameters to have http:// as a prefix, to calculate the full URL, such as: return redirect (‘ http://127.0.0.1:8000/dep/2/ ‘) and return redirect (‘ http:// URL/’).

Parameter is the URL

But without http:// and https://, the redirect() function looks for a match in the urls.py file, directs it to the URL if there is a match and executes the corresponding view function, and redirects it to the address if there is no match.

return redirect(‘/dep/66/’)