Click here to Skip to main content
15,884,176 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I know how to reverse a loop inside the template: {% ... | reverse %}

But I cannot do the same thing when the for loop is inside views.py.

I cannot find a syntax for this.

What I have tried:

import requests
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from .models import City

# Create your views here.
def user_homepage(request):
    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=38e4fec38e509c018629074ac1754906'
    city = 'London'
    
    cities = City.objects.all()
    
    weather_data = []
    
    for city in cities:
    
        r = requests.get(url.format(city)).json()
        
        city_weather = {
            'city': city.name,
            'temperature' : r['main']['temp'],
            'description' : r['weather'][0]['description'],
            'icon' :  r['weather'][0]['icon'],
        }
        
        weather_data.append(city_weather)
        
        result = {'city_weather' : city_weather}
        return render(request, 'userhomepage.html', result)
    
# def post(self, request):
Posted
Updated 3-Nov-19 21:03pm
Comments

Maybe you can use reverse in your City class to return the result, something like this:
Python
return reverse(bla, blabla)

Also see: Django Tutorial Part 6: Generic list and detail views - Learn web development | MDN[^]
class Author(models.Model):
...
return reverse('author-detail', args=[str(self.id)])
 
Share this answer
 
I found some documentation on page 140 here:
Sams Teach Yourself Django in 24 Hours - Brad Dayley - Google Boeken[^]
{% for title in books reversed %}

Although the chapter is about Views, it might still be a template thing, this is not very clear ...
 
Share this answer
 
v2
Comments
Ves93 4-Nov-19 4:09am    
It actually turns out that I do need to do a for loop in the template, and I did try to reverse in the template - with the correct syntax - but, for some reason, it doesn't work. It does NOT raise any errors, but it refuses to reverse the order; it keeps the original order.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900