Django template object property lookup with a dynamic variable name

谁说我不能喝 提交于 2019-12-08 07:42:41

问题


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

The ranking system 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


回答1:


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.



来源:https://stackoverflow.com/questions/7647966/django-template-object-property-lookup-with-a-dynamic-variable-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!