user596500
user596500

Reputation: 63

Django how to call this def in all template files?

Hey, i need a little help with this django function. I wan't to insert it into base.html but i cant .. How ?

def my_friends(request):
friendships = request.user.profile.friendships.exclude(pending=True).order_by('-friend__user__last_activity_date')
friendshipsQS = friendships
results = tuplify(friendships.all(), n=3)
return render(request, 'base.html', locals())

Upvotes: 1

Views: 298

Answers (1)

Accept Answers

You can't just set up a view that renders base.html and hope everything that extends it will use that view as well.

You need to use something like a Context Processor to inject values into every context. http://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors

def FriendsContextProcessor(request):
    """
    Include Friendships in all RequestContext
    """
    friendships = request.user.profile.friendships.exclude(pending=True).order_by('-friend__user__last_activity_date')
    friendshipsQS = friendships
    results = tuplify(friendships.all(), n=3)
    return { 'results': results, 'friendshipsQS': friendshipsQS }

add python.dot.path.to.my.FriendsContextProcessor to your TEMPLATE_CONTEXT_PROCESSORS setting and the dictionary returned above will be available in all RequestContext, which apparently render(...) does for you! Does that mean you're using trunk?

Upvotes: 1

Related Questions