开发者

Django, template context processors

开发者 https://www.devze.com 2022-12-19 18:35 出处:网络
I have a weird problem, I want to add a global query using context processors. This is how I did it by following:

I have a weird problem, I want to add a global query using context processors. This is how I did it by following:

made a processor.py in my app as such:

from myproject.myapp.models import Foo

def foos(request):
    return {'foos': Foo.objects.all()}

and at the end of my setting.py I have added this:

开发者_运维知识库TEMPLATE_CONTEXT_PROCESSORS = ('myapp.processor.foos',)

Lastly I pass my view as this:

def index_view(request):

    return render_to_response('index.html', {}, context_instance=RequestContext(request))

and at my index.html template:

<select id="select_foo">
{% for foo in foos %}
    <option value="/{{ foo.slug }}">{{ foo.name }}</option>
{% endfor %}
</select>

And lastly my url:

(r'^$', 'myapp.views.index_view'),

My foos display without any problem, however my media_url and other contexts are gone. What can be the issue


You need to add the default values of TEMPLATE_CONTEXT_PROCESSORS. However, instead of hard-coding those values, which will be tied to a specific version of Django, you can append your context processor to the default values by the following:

from django.conf import global_settings
TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
    "myapp.processor.foos",
)

Make sure to include the trailing comma in the tuple, so that Python recognizes it as a tuple.


When you specify this:

TEMPLATE_CONTEXT_PROCESSORS = ('myapp.processor.foos',)

In your settings file, you are overriding the Django's default context processors. In order to extend the list, you need to include the default ones in your settings:

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.core.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "myapp.processor.foos",
)

Note, the settings above are the defaults (plus your processor) for django 1.1.


Here what worked for me for Django 1.3

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.contrib.messages.context_processors.messages",
    "myapp.processor.foos", )
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号