0

I want to have a tag list of 10 main tags but displayed in random order because the font weight will determine their weight.

first i order objects and get 10 tags, than I use shuffle to randomise the order. So far it works. My issue now is to use {{forloop.counter0}} in template which outputs below code in random order:

 <tr> <td class="tag-0">Tag3</td> </tr> <tr> <td class="tag-1">Tag1</td> </tr> <tr> <td class="tag-2">Tag2</td> </tr> 

Instead I want it to be like this:

<tr> <td class="tag-2">Tag3</td> </tr> <tr> <td class="tag-0">Tag1</td> </tr> <tr> <td class="tag-1">Tag2</td> </tr> 

template:

{% for t in tags %} <tr> <td class="tag-{{forloop.counter0}}">{{t.title}}</td> </tr> {% endfor %} 

in views:

tags = list(Model.objects.order_by('title')[:10]) random.shuffle(tags) 

1 Answer 1

1

I would create a model manager to do your initial filtering, and then randomize the order of the objects in your view. You want to try to take a "fat" model, "thin" view approach. The more you can do in your model, the easier changes will be down the road. For example,

models.py:

class FooManager(models.Manager): def get_titles(self): return super(FooManager, self).get_queryset.order_by('title') class Foo(models.Model): title = models.CharField(max_length=120) objects = FooManager() def __unicode__(self): return self.title 

views.py:

def view(request): get_titles = Foo.objects.get_titles()[:10] titles = list(get_titles) random.shuffle(titles) context = { 'titles': titles } return render(request, 'template.html', context) 

Your templates become a lot easier, too.

html:

{% for t in titles %} {{ t.title }} {% endfor %} 

I hope that helps! Good luck!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.