views:

240

answers:

1

I use some third-party template tags in my Django Application (maintained elsewhere) that return a username as a string I can access in my templates like this.

{% for user in gr.user.foll.list %}

 {{user}}

Trouble is because {{user}} is returned as a string - I need to convert into a Django User Object, if it exists in the Django DB, or set a varible unRegistered if not so I can do things like:

 { user.get_profile.about }} # get profile information

So I thought I would write my first Django Template Tag so I could use it like this:

{% webapp_user_lookup user %} # my custom tag
    {% ifnot unRegistered %}
    {{ user.get_profile.about }} # get profile information - would fail with a string
    {% endifnot %}
 {% endfor %}

The code I use elsewhere to look up a user in a view is:

try:
        user = User.objects.get(username__iexact=user)
        unRegistered = False
        if not other_user.is_active:
                unRegistered = True
 except: 
        unRegistered = True

However looking at the Django Template tag examples I'm having trouble understanding how best to structure the custom template tag, to take my string username - and send back the results as an object if they exist, or set a varible if not and the original string. I'd really like to better understand how the structure works, and if I need a 'class' and if so, why. (I'm new to programming).

+3  A: 

use a template filter like so:

{{username|get_user}}

in your user_template_tags.py:

from django import template
from django.contrib.auth.models import User

register = template.Library()

########################

def get_user(username):
    try:
        user = User.objects.get(username__iexact=username)
    except User.DoesNotExist: 
        user = User.objects.none()
    return user

register.filter('get_user',get_user)

then in your template you can do something like:

{% with username|getuser as user %}
{% if user %}DO USER STUFF
{% else %}DO UNREGISTERED STUFF
{% endif %}
{% endwith %}
Brandon H
note that where you put {{user}} i used {{username}}
Brandon H
also, unless you've compensated for it in the user's save method, django can store a username of JOESHMO and joeshmo which would throw an error. You could leave off the "User.DoesNotExist" part if that is not handled.
Brandon H
Brandon this looks really simple and I can understand your code - I'm just going to play with it now, thank you for taking the time to write such a clear example.
Tristan
Thats brilliant, and I can use your syntax for a lot of other things in my webapp, thanks again
Tristan
no problem. you can use filters like this for all kinds of stuff. if you ever need to, you can pass another variable with {{var1|filtername:var2}} and def filtername(var1,var2) in your *tags.py
Brandon H