How to get request.user in TemplateTag

How to get request.user value in 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 news_list.html file, and templatetag generally works. I just couldn't get the request.user value in this templatetag.

Would thank all pointers. Thank you Kevin

+4
source share
4 answers

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.

+2
source

... it might look like this:

  u = context['request'].user 
+11
source

If this tag takes_context , then after adding django.core.context_processors.request in settings.CONTEXT_PROCESSORS, the context ['request'] will appear.

In addition, after adding django.contrib.auth.context_processors.auth to settings.CONTEXT_PROCESSORS, the context ['user'] will exist.

+1
source

Just clarify the solution description a bit.

In your settings module, set (or create) the CONTEXT_PROCESSORS variable as follows:

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

Then in your view templates, you can simply use {{user.username}} to link to your current user object.

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

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

See SO thread: Always include user in django template context

0
source

All Articles