简体   繁体   中英

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.

At the template, I can check if user logged in via facebook by checking request.facebook.uid such as:

{% 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:

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.

If I pass 'is_facebook': request.facebook.uid in every single view , it works but I need this globally for any view rendering.

If you have access via the request object, why do you need to add a special is_facebook boolean at all? 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:

{% 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. You can probably debug and see when the facebook middleware is modifying the request and when your context processor is invoked. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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