文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Django RequestContext Example

Django RequestContext Example

时间:2009-04-05  来源:cobrawgl

Browsing other peoples’ code is a great way to learn new things about a language or framework. I never made it to the Django docs about Contexts, but the Pinax developers apparently did and I got a chance to learn this from them. This is a few sections of their code and how they use RequestContext in their apps.

If you are looking at the source of some of their views you might see how they are using it. Here is what it looks like in friends_app.friends

 return render_to_response(template_name, { "join_request_form": join_request_form, "invites_received": invites_received, "invites_sent": invites_sent, "joins_sent": joins_sent, }, context_instance=RequestContext(request))

So what extactly does context_instance=RequestContext(request) do? I took a look at the django documentation to find out more. And that led me to check the settings file and I found that there were quite a few things listed in TEMPLATE_CONTEXT_PROCESSORS.

TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.request",   "notification.context_processors.notification", "announcements.context_processors.site_wide_announcements", "account.context_processors.openid", "account.context_processors.account", "misc.context_processors.contact_email", "misc.context_processors.site_name", "messages.context_processors.inbox", "friends_app.context_processors.invitations", "misc.context_processors.combined_inbox_count", )

I opened up friends_app.context_processors to see a bit more and it looked like this

from friends.models import FriendshipInvitation   def invitations(request): if request.user.is_authenticated(): return { 'invitations_count': FriendshipInvitation.objects.filter( to_user=request.user, status="2").count(), } else: return {}

This means that every view that has context_instance=RequestContext(request) in it will call the above function since it is listed in settings.py and it will provide the template variable, {{ invitations_count }}.

Using RequestContext makes it easy to have the common template variables available on every page and I will have to start using it more in my apps. So make sure you have from django.shortcuts import render_to_response and from django.template import RequestContext in your file and add your context processor to the settings file and you should be ready to add template vars to your contexts.

排行榜 更多 +
找茬脑洞的世界安卓版

找茬脑洞的世界安卓版

休闲益智 下载
滑板英雄跑酷2手游

滑板英雄跑酷2手游

休闲益智 下载
披萨对对看下载

披萨对对看下载

休闲益智 下载