1

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 %}
Andrew Nguyen
  • 1,416
  • 4
  • 21
  • 43
  • do you need **only one** item? if so, why does your response have a list of items? – Andres Dec 12 '14 at 21:08
  • I basically need one random article each time the page reloads. I mentioned those four things above, was my attempt to clarify that those four pieces of info should relate to the one random article from the database. – Andrew Nguyen Dec 12 '14 at 21:19
  • did you see karthikr's answer? return only one object if you don't need more – Andres Dec 12 '14 at 21:21
  • check this http://stackoverflow.com/questions/7162629/django-shuffle-in-templates#answer-7162816 – Andres Dec 12 '14 at 21:43

1 Answers1

4

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.

karthikr
  • 97,368
  • 26
  • 197
  • 188
  • I'm confused what .py file to put your first snippet that you mentioned and what I need to rename "myview" and "Mymodel" to. – Andrew Nguyen Dec 12 '14 at 23:27
  • Seriously? Do you have views named `myview`, etc? This was only an example. In your views.py file, whatever view method is sending the context into the template should be doing this – karthikr Dec 13 '14 at 01:01
  • Still pretty new to Django, so I'm learning the terms. My first piece of clarification is "Would I put def myview(request): random_object = MyModel.objects.order_by('?').first() in models.py or views.py" – Andrew Nguyen Dec 16 '14 at 00:49
  • Sorry. I did not mean to be harsh. In your view which would render the template showing the random queryset object would have this code. – karthikr Dec 16 '14 at 02:59