Andrew Nguyen
Andrew Nguyen

Reputation: 1436

Randomizing content in Django using for loop

I'm trying to get a different article from my database of 10 articles using Django to be random every time the page is refreshed. Each article consists of four pieces of information:

article.pubDate
article.author
article.heroImage
article.body

I've used a for loop {% for article in object_list|slice:":1" %} to get a single article, but I don't know if there's something like random or shuffle that I can tack onto my for loop.

list.html

{% for article in object_list|slice:":1" %}
    <div class="mainContent clearfix">
        <h1>Top 10 Video Games</h1>
        <p class="date">{{article.pubDate|date:"l, F j, Y" }}</p> | <a href="" class="author">{{article.author}}</a>
        <img src="{{article.heroImage}}" alt="" class="mediumImage">
        <p class="caption">{{article.body|truncatewords:"80"}}</p>
{% endfor %}

Upvotes: 1

Views: 700

Answers (1)

karthikr
karthikr

Reputation: 99660

How about fetching a random object from the view instead of the object list ?

Example

def myview(request):

    random_object = MyModel.objects.order_by('?').first() #or [0] if < django 1.6

    #Send this in the context..

And now reference this in the template instead of slicing a whole object list.

If you do need an object list, just do

random_list = MyModel.objects.order_by('?')

which would load a random list every time.

Here is the documentation. Note that this could be a little expensive though.

Upvotes: 4

Related Questions