Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get dictionary of RequestContext imported from django.template

Tags:

python

django

I have the following code in my django project.

ctxt = RequestContext(request, {
    'power': power,
    'attack': attack,
    'defense': defense,
    })  

Now I want get this dictionary like below through ctxt

{
    'power': power,
    'attack': attack,
    'defense': defense,
}

I tried ctxt.dicts, but this contains too many items. So I see into the source code, and find these code in class RequestContext(Context):

for processor in get_standard_processors() + processors:
    self.update(processor(request))

which I think bring in the other items.

So how can I get that?

Btw, if you want to know why I want to do this, you can see this question I asked before.

How can I get a rewritten render_to_response to get a json in django with the least changes to the whole project

like image 902
pktangyue Avatar asked Jan 21 '13 08:01

pktangyue


People also ask

How do you loop a dictionary in a Django template?

To iterate through dictionary in a dictionary in a Python Django template, we can loop through the items with a for loop. to loop through the data dict's entries with a for loop. We get the key value pairs with data.

What is RequestContext Django?

Context, but Django also comes with a subclass, django. template. RequestContext, that acts slightly differently. RequestContext adds a bunch of variables to your template context by default – things like the HttpRequest object or information about the currently logged-in user.

How do I sort a dictionary in Django?

You can't sort a dictionary, you can sort representation of a dictionary. Dictionary has a random ordered members. I hope this helps. If i'm doing this: sorted_dict = sorted(data['scoruri'].

What is context processor in Django?

A context processor is a Python function that takes the request object as an argument and returns a dictionary that gets added to the request context. They come in handy when you need to make something available globally to all templates.


2 Answers

I'm a bit late to the party, but you can get a dict from your RequestContext object with

ctxt.flatten()

if you're using Django>=1.7. (Docs)

like image 167
kavdev Avatar answered Oct 13 '22 21:10

kavdev


ctxt.dict is stack of dictionaries, so you only need to:

ctxt.dict[0]
like image 36
Lukasz Koziara Avatar answered Oct 13 '22 20:10

Lukasz Koziara