开发者

Django template object property lookup with a dynamic variable name

I have a table with user, rank, squat, deadlift, benchpress, Clean and Jerk and Snatch.

The ranking sy开发者_Go百科stem will rank any number of combinations from just total amount Squated, to total amount benchpressed and deadlifted to the total amount lifted across all five disciplines. As you can see there is a huge number of available combinations that a user can check their rankings by. While i have as yet to painstakingly add all these ranking combinations to my database i have done the main 5 ie SQ_rank.

In my views file i have done the following, where request.GET gets either 'SQ', 'DL', 'BP', 'Snatch' or 'CJ':

def rankings()
    a = ''
    for i in request.GET:
        a += i    
    b = a + '_rank'    
    query_results = UserProfile.objects.all().order_by(a)
    rank = b
    return render_to_response('registration/rankings.html',{'query_results': query_results, 'rank': rank,}, context_instance=RequestContext(request, processors=[custom_proc])) 

Now i want the rank as a variable inside of my template. it will return something _rank such as SQ_rank or DL_rank, which is in my database.

{% for item in query_results %}
    <tr>
    <td>{{ item.user }}</td>
    <td>{{ items.??? }}</td>
    <td>{{ item.SQ }}</td>
    <td>{{ item.DL }}</td>
    <td>{{ item.BP }}</td>
    <td>{{ item.CJ }}</td>
    <td>{{ item.Snatch }}</td>
    </tr>
{% endfor %}

How do i do this without having a heap load of {% ifequal %}} tags accounting for all the varaible combinations that will be available when i get around to adding them to my database? Does all this make sense


First of all:

for i in request.GET:

is invalid since request.GET is a dict, not a list. If what you mean by item.??? is to lookup the item property whose name is contained in the "rank" variable, this is what I use for this purpose:

{{ item|ofKey:rank }}

The "ofKey" is a custom template filter. Create a file called, say, extra.py which contains:

from django import template
register = template.Library()

@register.filter
def ofKey(value, arg):
    if value:
        return value.get(arg)
    else:
        return ""

Now save this file in a "templatetags" subdirectory of one of your app directories. You will need to use:

{% load extra %}

at the beginning of the templates where you will need it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜