This article describes how to use the locals () function in Django. Django is one of the most famous popular Python frameworks, for more information about how to assign values to current_datetime, see:
def current_datetime(request): now = datetime.datetime.now() return render_to_response('current_datetime.html', {'current_date': now})
Many times, as in this example, you find that you have been calculating a variable and saving the result to the variable (such as now in the previous Code ), then, send these variables to the template. Programmers who like to be lazy should note that it is a little redundant to constantly name temporary variables and templates. It is not only redundant, but also requires additional input.
If you are a programmer and want to make the Code look more concise, you can use the Python built-in function locals (). It returns a dictionary to map the names and values of all local variables. Therefore, the preceding view can be rewritten as follows:
def current_datetime(request): current_date = datetime.datetime.now() return render_to_response('current_datetime.html', locals())
Here, we do not manually specify the context dictionary as before, but pass in the locals () value, which includes all the variables defined by the function execution to this time point. Therefore, we rename the now variable to current_date, because that is the expected variable name of the template. In this example, locals () does not bring many major improvements, but if you want to define multiple template variables and want to be lazy, this technology can reduce some keyboard input.
When using locals (), note that it will include all the local variables, which may be more accessible than the template you want. In response, locals () also contains the request. It depends on your application.