Anish Menon
Anish Menon

Reputation: 809

Shuffle loop Django

views.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)

Can you please answer template tag , how to shuffle 'ads_right' and 'ads_left' on each refresh .

Upvotes: 2

Views: 480

Answers (1)

Samuele Mattiuzzo
Samuele Mattiuzzo

Reputation: 11048

Shuffle them in your views:

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)

If you want a templatetag, you could use something like this:

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

And then in the templates:

{% for item in ads_left|shuffle %}

Upvotes: 1

Related Questions