views:

172

answers:

1

Hello All,

I have a custom filter user_tz which takes user as an argument. It works fine everywhere, but when I tried to use this filter in the regroup tag it fails saying that user does not exist.

The code:

{% regroup proj_messages.object_list by created_on|user_tz:user as proj_message_list %}

This is the error I am getting: Caught an exception while rendering: Failed lookup for key [user] in u"Today's tasks".

Thanks, Masood Ahmed

A: 

Strangely even I came across this exactissue. Though later I had to change my code, i couldn't get on its solution. Apparently what happens is something like as follows.

Whatever you write in templates, is splitted as Nodes, Variables etc. Variables, at time of rendering is searched in context available to that instance. And please note that, for regroup tags, the context available, is just that object_list, which you passed as first argument. Not the usual context(which contains 'user' in your case), which is global to whole template. So, it is unable to find any other variable you specified, which is not in you object_list.

Thus, in your case, the context available to regroup is an object from proj_messages.object_list. And so the resolver code is able to find variable created_on in context, but not user. And that is what throwing the template exception here.

Considering this just imagine, what would happen, if your object_list too, have had the user attribute. In that case there wont be any KeyError, but user passed to the filter, would be not at all the user variable you intended to pass.

Edit on request: There is not direct way, to pass the user to the such use of filter in regroup tag. But a kind of hack will obviously work. Note, its just a hack. Make each individual entity/object of proj_messages.object_list to contain that user variable from view or using an extra filter on object_list from template. But better than that, if you want user to be available anywhere, from outside the context, i would like you to consider yet another hack. Check out, http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser .

simplyharsh
So is there any way I can pass user variable to my filter?