tags:

views:

52

answers:

3

I'd like the simplest way to show "You" instead of a username if that username matches that of the current user.

ideally a filter like this (where object.owner is a ForeignKey field pointing at auth.User)

{{ object.owner|username_or_you }}

or a way to intercept this higher up the chain - so anywhere i output user.username it'll output "You" or the actual username in question.

currently I have this:

{{ object.owner|username_or_you,request.user }}

where the filter looks like this:

def username_or_you(user, request_user):
if user == request_user:
    return "You"
else:
    return user
A: 

I would like to comment on that question but I currently lack the reputation to do so, alas my reply in "answer form":

What exactly is your problem? I ask this as you already provide the boilerplate code for a nice little custom template filter. You can read about custom filters at http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters . All you need to do is to wrap your code into the filter class and import it in the templates you want to use the filter. :)

markmywords
the issue is being able to call that filter but without passing in the user. I have this filter set up and working fine, I just wanted to see if there was a way for a filter to get hold of the request object without passing it in.
Guy Bowden
A: 

I think your problem is that you're using a comma instead of a colon in the filter.

so... your code:

{{ object.owner|username_or_you,request.user }}

should be:

{{ object.owner|username_or_you:request.user }}

Then the current user will be passed as the second argument to the filter

Jiaaro
yes - that was a typo - my question is how I could just dump the second argument to save typing "request.user" where ever it's called.
Guy Bowden
That requires a template tag. See Zach's answer :)
Jiaaro
A: 

You can use an inclusion tag

Django | Custom template tags and filters

You can register it with takes_context=True and then access it in the tag using context['request'].user

Personally I would just feed the user into a filter as suggested by Jim, but this in another option.

Zach