pythondjango

AttributeError: 'module' object has no attribute 'Business'


This is the /app03/views.py:

from django.db import models

def business(request):
    v = models.Business.objects.all()   # this is the line10
    # QuerySet
    # [obj(id, caption, code), obj,obj...]
    return render(request, '/app03/business.html', {'v':v})

This is the traceback information in my PyCharm CE:

Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/luowensheng/Desktop/TestIOS/TestPython/pyProject/app03/views.py", line 10, in business
    v = models.Business.objects.all()
AttributeError: 'module' object has no attribute 'Business'
[14/Aug/2017 09:27:27] "GET /app03/business/ HTTP/1.1" 500 64817

In my /app03/models.py:

class Business(models.Model):
    caption = models.CharField(max_length=32)
    code = models.CharField(max_length=32, default='SA')

and, I have done this operation:

python manage.py makemigrations
python manage.py migrate 

and in the db.sqlite3, have generated the app03_business table:

enter image description here

Why there is no attribute 'Business'?


Solution

  • You should import the class from your app model directly. You're currently in conflict with Django's models module, which has has the same name models with that in your app:

    from django.db import models
    from app03.models import Business
    
    def business(request):
        v = Business.objects.all()   # this is the line10
        # QuerySet
        # [obj(id, caption, code), obj,obj...]
        return render(request, '/app03/business.html', {'v':v})