简体   繁体   English

Django:模板上下文处理器请求变量

[英]Django: Template context processor request variable

I am trying to implement django-facebookconnect , for I need to check if a user logged in via Facebook or a regular user. 我正在尝试实现django-facebookconnect ,因为我需要检查是通过Facebook还是普通用户登录的用户。

At the template, I can check if user logged in via facebook by checking request.facebook.uid such as: 在模板上,我可以通过检查request.facebook.uid来检查用户是否通过facebook登录,例如:

{% if is_facebook %}
{% show_facebook_photo user %}
{% endif %}

For this, I need to pass is_facebook': request.facebook.uid to the template and I will be using this in everywhere thus I want tried to apply it to an existing template context processor and call the snipplet above at the base.html, and it works fine for Foo objects: 为此,我需要将is_facebook': request.facebook.uid传递给模板,并且将在各处使用它,因此我想尝试将其应用于现有的模板上下文处理器,并在base.html上调用上述代码片段,对于Foo对象也可以正常工作:

def global_variables(request):
    from django.conf import settings
    from myproject.myapp.models import Foo
    return {'is_facebook': request.facebook.uid,'foo_list': Foo.objects.all()}

I can list Foo objects at any view without any issue however it fails for this new is_facebook , it simply returns nothing. 我可以在任何视图中列出Foo对象,没有任何问题,但是对于这个新的is_facebook ,它失败了,它什么也没返回。

If I pass 'is_facebook': request.facebook.uid in every single view , it works but I need this globally for any view rendering. 如果我在每个视图中都传递'is_facebook':request.facebook.uid,它可以工作,但是对于任何视图渲染,我都需要全局使用。

If you have access via the request object, why do you need to add a special is_facebook boolean at all? 如果您可以通过request对象进行访问,那么为什么根本需要添加一个特殊的is_facebook布尔值? Just enable the built-in django.core.context_processors.request and this will ensure that request is present in all templates, then you can do this: 只需启用内置的django.core.context_processors.request确保所有模板中都存在该request ,那么您可以执行以下操作:

{% if request.facebook.uid %}

It could be a timing issue. 这可能是一个时间问题。 Make sure that the Common middleware comes before the facebook middleware in your settings file. 确保您的设置文件中的通用中间件位于Facebook中间件之前。 You can probably debug and see when the facebook middleware is modifying the request and when your context processor is invoked. 您可能可以调试并查看何时Facebook中间件正在修改请求以及何时调用上下文处理器。 That may give you some clue as to why this is happening. 这可能会为您提供一些有关为什么发生这种情况的线索。 But, as Daniel said, you can always just use the request object in your templates. 但是,正如Daniel所说,您始终可以只在模板中使用request对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM