Ian Mobbs Ian Mobbs - 1 year ago 78
Python Question

Can't use .update() function on Django context in views?

I have a function that gets some base information in my

file, and I'm trying to update the context of each page using it by having it return a dictionary. However, using
on the context dictionary in the
function doesn't seem to work.

Here's what I'm doing:

def getBaseInfo():
allPages = list(Page.objects.all())
primaryPages = allPages[:5]
secondaryPages = allPages[5:]
return {'p':primaryPages, 'p2':secondaryPages}

def index(request):
return render(request, 'pages/index.html', {}.update(getBaseInfo()))

However, nothing is sent to my templates. Thanks in advance!

Edit: I'm using Python 2.7.11

Answer Source

Firstly, if you wanted to use a base dictionary and add objects to that you should do so explicitly:

def index(request):
    context = getBaseInfo()
    context.update({'otherkey': 'othervalue'})
    # or
    context['otherkey'] = 'othervalue'

However, there is no need to do this at all. Django already provides you a way of automatically providing shared context, and that is a context processor.

In fact your getBaseInfo() function is already almost a context processor - it just needs to accept the request parameter - so you just need to add it to the context_processors list in your TEMPLATES setting. Then all your templates will automatically get the values from that function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download