I am new to Django. I am working on a project that uses weather API to get the weather.Everything was working fine until models.py was made and imported city on views.py
I use ver. 1.11.13
models.py
from __future__ import unicode_literals
from django.db import models
class city(models.Model):
name = models.CharField(max_length=25)
def __str__(self):
return self.name
class Meta:
verbose_name_plural ='cities'
views.py ( Error comes at cities = city.objects.all())
import requests
from django.shortcuts import render
from .models import city
def index(request):
url= 'http://api.openweathermap.org/data/2.5/weather?q={}& units=imperial&appid=e1a2ef38103d2e572d316e38452e2acd'
city = 'Lucknow'
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)
print(weather_data)
context = {'weather_data' : city_weather}
return render(request,'weather/weather.html', context)
In your index
function, you write:
def index(request):
url= 'http://api.openweathermap.org/data/2.5/weather?q={}& units=imperial&appid=e1a2ef38103d2e572d316e38452e2acd'
city = 'Lucknow'
cities = city.objects.all()
# ...
As a result, you defined city
here as a locally scoped variable, and with a string value. A quick fix is to rename the string, like:
def index(request):
url= 'http://api.openweathermap.org/data/2.5/weather?q={}& units=imperial&appid=e1a2ef38103d2e572d316e38452e2acd'
city_ = 'Lucknow'
cities = city.objects.all()
# ...
# use city_ for the string element
But nevertheless, a class typically starts with an uppercase, so I would advice to rename your class City
instead of city
.
Furthermore I find it weird that you defined this string, since nowehere in the view, you are supposed to use it. The url.format(..)
should probably use the city.name
of the City
object in the queryset.
Solve this issue.
For dynamic table name you can use like
table_name = 'MyTable'
model = getattr(YOURAPP.models, table_name)
model.objects.all()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With