Typically, we usually load a template file, then render it in context, and finally return the processed HttpResponse object to the user. We have optimized the scenario by using the Get_template () method instead of the cumbersome code to work with the template and its path. But it still takes a certain amount of time to knock out these simplified codes. This is a ubiquitous repetition of menial labor. Django provides a quick way for you to load a template file, render it, and return it as a httpresponse.
The shortcut is a function named Render_to_response () in the Django.shortcuts module. In most cases, you will use the "\" Object unless your boss measures your work by the number of lines of code.
System MESSAGE:WARNING/2 (
, line 1736); backlinkinline literal start-string without end-string. System MESSAGE:WARNING/2 (
, line 1736); backlinkinline literal start-string without end-string. System MESSAGE:WARNING/2 (
, line 1736); backlinkinline literal start-string
without end-string.
The following is an example of a current_datetime that has been rewritten using render_to_response ().
From django.shortcuts import render_to_responseimport datetimedef current_datetime (Request): now = Datetime.datetime.now () return render_to_response (' current_datetime.html ', {' current_date ': now})
Big changed! Let's take a step-by-step look at the code changes:
We no longer need to import get_template, template, Context, and HttpResponse. Instead, we import django.shortcuts.render_to_response. Import datetime continues to persist.
In the Current_datetime function, we still perform now calculations, but template loading, context creation, template parsing, and HttpResponse creation are all done in the call to Render_to_response (). Because Render_to_response () returns the HttpResponse object, we only need to return the value in the view.
The first parameter of Render_to_response () must be the name of the template to use. If you want to give the second argument, the argument must be the dictionary that is used to create the Context for the template. If you do not provide a second argument, Render_to_response () uses an empty dictionary.