products = random.sample(products, 9)
return render(request, 'front-page.html', {'products': products})
It's actually as simple as this!
First we import random from Python. Then we create a new view and get products from the database.
The function we use for randomizing the products only works with lists, so we need to convert the queryset to a list. A queryset is by default a dictionary.
When we have the list, we can randomize this by running "random.sample". We pass in the list and the number of products we want.
Build an e-commerce using Django
Want to learn how to build an e-commerce from scratch using Django?
Check out the playlist on my YouTube channel here:
https://www.youtube.com/watch?v=bAG_Ia8LX-M&list=PLpyspNLjzwBmIDrDOaPkLLuy5YDDNW9SA
Code With Stein
Learn how to build web sites and web applications using technologies like Django, Vue, Htmx, Tailwind, Bulma and many more.
YouTube
Twitter
Discord
Patreon