2

视图.py

def mainpage(request):

    ads_right = Ads.objects.select_related().all().filter(ads_section = 'R')
    ads_left = Ads.objects.select_related().all().filter(ads_section = 'L')

    variables = RequestContext(request, {'ads_right': ads_right,'ads_left': ads_left})
    return render_to_response('index.html', variables)

您能否回答模板标签,如何在每次刷新时随机播放“ads_right”和“ads_left”。

4

1 回答 1

1

在您的视图中随机播放它们:

ads_right = Ads.objects.select_related().all().filter(ads_section = 'R').order_by('?')
ads_left = Ads.objects.select_related().all().filter(ads_section = 'L').order_by('?')

# return things as always
variables = RequestContext(request, {'ads_right': ads_right,'ads_left': ads_left})
return render_to_response('index.html', variables)

如果你想要一个模板标签,你可以使用这样的东西:

@register.filter
def shuffle(arg):
    # slice it, cast it to list
    my_list = list(arg[:])
    random.shuffle(my_list)
    return my_list

然后在模板中:

{% for item in ads_left|shuffle %}
于 2013-07-08T09:56:29.970 回答