4

How does one get in the value of request.user into a TemplateTag?

In the file myproject/news/templatetags/news_tags.py I have:

from django import template
from myproject.news.buildnews import BuildNewsList
from django.contrib.auth.models import User
from django import http
from django.contrib import admin
from django.template import RequestContext

register = template.Library()

def news_now (context):
    #who = request.user  ## this doesn't work
    news = BuildNewsList()
    entries = news.buildnewslist()
    return {'entries': entries, 'who': who, }

register.inclusion_tag('news_list.html', takes_context=True)(news_now)

Separately I have a file news_list.html and overall the templatetag works. I just haven't been able to pull in the value of request.user in this templatetag.

Would appreciate any pointers. Thanks. Kevin

4 Answers 4

12

... it could look like this:

 u = context['request'].user
0
2

Do you have django.core.context_processors.request in your settings.CONTEXT_PROCESSORS? If so, make the first argument to the tag the request object and then you should be fine.

0
1

If that tag takes_context, then after adding django.core.context_processors.request to settings.CONTEXT_PROCESSORS there will be context['request'].user available.

Moreover, after adding django.contrib.auth.context_processors.auth to settings.CONTEXT_PROCESSORS, there will be context['user'].

0

Just to be a little clearer on the description of the solution.

In your settings module, set (or create) the CONTEXT_PROCESSORS variable like so:

CONTEXT_PROCESSORS  = (
    'django.contrib.auth.context_processors.auth'
)

Then in your view templates you can simply use {{ user.username }} to refer to your currently logged in user object.

This works because the django.contrib.auth.context_processors.auth module adds the 'user' variable to the context dictionary. This is nearly equivalent to:

ReqCon = RequestContext(Request, {'user' : Request.user})
html = t.render(ReqCon)
return HttpResponse(html)

See SO thread: Always including the user in the django template context

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.