Tips for using the locals () function in Django

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.