Django using locals() [duplicate]

2024/10/9 16:30:16

I am beginner in web development with Django. I have noticed that the locals() function is used instead of the context dictionary that I am used to see.

From what I see on the internet locals() is pretty useful, so are there any special cases where this is not true and its better to use the context_dictionary?

Answer

Using locals() in that tutorial is just for convenience, since all the data he needs to pass to the template is stored in local variables. locals() returns a dictionary holding the local variables names (as keys) and the current values (as values).

You need to use an explicit context_dictionary, instead of passing locals(), if you must build your data and you don't have such data in separate variables.

both locals() and context_dictionary are dictionaries, and that's the only requirement: a dictionary-like object (i.e. an object supporting __getitem__(key) and get(key, default=None) methods). How you get the dictionary, is up to you. There's no practice about that, but alternatives are:

  • Return a RequestContext(), which is a dict-like object, if you use CONTEXT_PROCESSORS.
  • Return locals() if you have the data in your local variables.
  • Return a hand-made dictionary with your data otherwise.

EDIT - Examples:

Example on building the dictionary on your own:

def my_view(request):return render_to_response('hello.html', {'full_name': u"%s %s" % (request.user.first_name, request.user.last_name),'username': request.user.username})

Example on building the dictionary from locals():

def my_view(request):full_name = u"%s %s" % (request.user.first_name, request.user.last_name)username = request.user.usernamereturn render_to_response('hello.html', locals())

Assume hello.html is - in either case:

<html><body>You are {{ full_name }} ({{ username }})</body>
</html>

You'll get the expected result.

https://en.xdnf.cn/q/69995.html

Related Q&A

python ghostscript: RuntimeError: Can not find Ghostscript library (libgs)

When trying to run hello-world exampleimport sys import ghostscriptargs = ["ps2pdf", # actual value doesnt matter"-dNOPAUSE", "-dBATCH", "-dSAFER","-sDEVICE…

what is the default encoding when python Requests post data is string type?

with fhe following codepayload = 工作报告 总体情况:良好 r = requests.post("http://httpbin.org/post", data=payload)what is the default encoding when Requests post data is string type? UTF8…

How to initialize a database connection only once and reuse it in run-time in python?

I am currently working on a huge project, which constantly executes queries. My problem is, that my old code always created a new database connection and cursor, which decreased the speed immensivly. S…

Django - ModelForm: Add a field not belonging to the model

Note: Using django-crispy-forms library for my form. If you have a solution to my problem that involves not using the cripsy_forms library, I accept it all the same. Not trying to be picky just need a …

Row by row processing of a Dask DataFrame

I need to process a large file and to change some values.I would like to do something like that:for index, row in dataFrame.iterrows():foo = doSomeStuffWith(row)lol = doOtherStuffWith(row)dataFrame[col…

Tweepy Why did I receive AttributeError for search [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

Running qsub with anaconda environment

I have a program that usually runs inside a conda environmet in Linux, because I use it to manage my libraries, with this instructions:source activate my_environment python hello_world.pyHow can I run …

Flask Application was not able to create a URL adapter for request [duplicate]

This question already has answers here:Flask.url_for() error: Attempted to generate a URL without the application context being pushed(3 answers)Closed 10 months ago.I have this code which used to work…

Python typing deprecation

The latest typing docs has a lot of deprecation notices like the following: class typing.Deque(deque, MutableSequence[T]) A generic version of collections.deque.New in version 3.5.4.New in version 3.6.…

Cant install tensorflow with pip or anaconda

Does anyone know how to properly install tensorflow on Windows?Im currently using Python 3.7 (also tried with 3.6) and every time I get the same "Could not find a version that satisfies the requi…