Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError at / 'str' object has no attribute 'objects'

Tags:

django

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)
like image 291
Adarsh Bahadur Avatar asked Sep 15 '25 12:09

Adarsh Bahadur


2 Answers

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.

like image 71
Willem Van Onsem Avatar answered Sep 18 '25 12:09

Willem Van Onsem


Solve this issue.

For dynamic table name you can use like

 table_name = 'MyTable'
 model = getattr(YOURAPP.models, table_name)
 model.objects.all()
like image 40
Nids Barthwal Avatar answered Sep 18 '25 11:09

Nids Barthwal