AttributeError: module 'django.db.models' has no attribute 'Models' - python

When I'm trying to migrate a new app onto the server i get this error
AttributeError: module 'django.db.models' has no attribute 'Models'- in terminal
I'm using PyCharm. I am very fresh to Django and web development so any tips will help. Thanks!
from django.db import models
# Create your models here.
class product(models.Model):
item = models.Textfiels()
description = models.Textfields()
price = models.Textfields()

There's no such class django.db.models.TextFields but this works for me on any recent version :
from django.db import models
class product(models.Model):
item = models.TextFiel()
description = models.TextField()
price = models.TextField()
You made 2 typos : the correct name is TextField and you typed Textfields (Python is case sensitive)
I suspect you didn't setup correctly your project under PyCharm. When correctly setup, it shows warnings on misspelled names (names underlined with red dots with default setting).

There's another variation to this question and that is in the form of:
AttributeError: module 'django.contrib.auth' has no attribute 'models'
As far as I can tell this is typically caused by conflicting imports or improperly imported files. Another cause could be changes to Django's updates but I'm not sure about that as I didn't find any documentation that changed that aspect of the Django library.
Short term solution to this is as follows:
from django.contrib.auth import models
class MyClass(models.User): """ """
This will allow you to at least test your runserver command and website on a browser of your choosing.
I'm still trying to figure out any other solutions to this problem that can be a fix for individually importing the 'auth' module itself.
At the time of this writing I'm using Django 2.2.6 whereas Django 2.2.7 is out and 2.2.8 is on the way to be released.

I'm not sure if this is the solution , but when I had this problem it was because in my admin.py file I had
from django.contrib import admin
from meetings.models import Meeting, Room
admin.site.register(Meeting, Room)
But changing it to solved the issue
from django.contrib import admin
# Register your models here.
from meetings.models import Meeting, Room
admin.site.register(Meeting)
admin.site.register(Room)

Related

Unable to call a class using Django

If I do that :
from myapp import models
User.objects.first()
I got that error :
NameError : name 'User' is not defined
whereas if I do that
import myapp
myapp.models.User.objects.first()
it works
I don't understand at all why I have that problem
Thank you very much for your help !
Replace:
from myapp import models
with the following:
This way, you are telling Django which model classes to import rather than leaving Django guessing what to do with it.
It prevents you from loading unnecessary models which might not be used right away and could potentially increase load time.
from myapp.models import User
In your example, your have not imported class User actually. You have imported it's module called models
You can do one of these:
from myapp import models
models.User.objects.first()
Or:
from myapp.models import User
User.objects.first()

Importing Model Class into another app - Django

I am trying to import a model class from another app. My structure looks like the following:
mysite/
-- main/
models.py
-- webshop/
models.py
I'd like to import a model class from my webshop app into the main/models.py. I run the following in my main/models.py file:
from django.db import models
from ..webshop.models import Item
# Create your models here.
class Test(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
In my text editor everything seems fine. It finds the appropriate app and finds the model class Item which I need to import there.
When I run makemigrations I am getting the following error:
ValueError: attempted relative import beyond top-level package
I've read some other questions on SO on how to make this work but can't figure it out. Tried:
mysite.webshop.models import Item
aswell. But then I get a: ModuleNotFoundError: No module named 'mysite.webshop'.
Does anyone have suggestions?
From the error ValueError: attempted relative import beyond top-level package, I'm going to assume in your text editor, your current working directory is mysite/. And so using ..webshop.models you're trying to go up two directories above mysite/ which is why you're getting the error.
What you need to do is:
from django.db import models
from webshop.models import Item

django oscar commerce: Conflicting 'stockrecord' models in application

I am using oscarcommerce for my django project. I want to extend the "StockRecord" model to include some more fields. So I forked the partner app as follows. (boscar is my app name)
python manage.py oscar_fork_app partner boscar/
It successfully forked and new files were added to boscar/partner folder. I added 'boscar.partner' in my installed apps.
Now I added new fields in StockRecord models as follows
boscar/partner/models.py
from django.db import models
from oscar.apps.partner.abstract_models import AbstractStockRecord
class StockRecord(AbstractStockRecord):
effective_price = models.FloatField(default=0, null=True)
is_instock_item = models.BooleanField(default=False, null=True)
instock_quantity = models.IntegerField()
from oscar.apps.partner.models import * # noqa
Now when I try to make migrations it shows the following error.
RuntimeError: Conflicting 'stockrecord' models in application 'partner': <class 'oscar.apps.partner.models.StockRecord'> and <class 'boscar.partner.models.StockRecord'>.
I already successfully forked the catalogue and order models and that are working fine. Only this "StockRecord" models showing this error.
That error can occur as a result of a circular import issue associated with Oscar's support for overriding models and classes.
You need to check for places where you're importing directly from oscar.apps.partner.models. These should be replaced by importing from boscar.partner.models or using oscar.core.loading.get_model.

ReferenceField in mongoengine

I use mongoengine with django. I have two applications with models.
app1/models.py:
from mongoengine import fields
from mongoengine.document import Document
class Model1(Document):
name = fields.StringField()
lists = fields.ListField(fields.ReferenceField("Model2", dbref=False))
app2/models.py:
from mongoengine import fields
from mongoengine.document import Document
class Model2(Document):
name = fields.StringField()
All applications were added to INSTALLED_APPS. When I use the django dev-server, everything is fine. But using this code with uwsgi-server there is an error:
Model2 has not been registered in the document registry.
Importing the document class automatically registers it, has it
been imported?
What I should do?
You should import app2.models somewhere. Put a comment by the import saying why it's there, so nobody removes the useless-looking import in the future.
When the django dev server starts up it imports the models from all installed apps and validates them. You'll see
Validating models...
0 errors found
This does not happen in a production environment. It is just a nicety of the dev server.

Python import problem with Django management commands

For whatever reason, when I was new to Python and Django, I wrote some import statements like this at the top of a models.py file:
from django.contrib import auth
And I'd use it like this:
class MyModel(models.Model):
user = models.ForeignKey(auth.models.User)
# ...
This worked fine. A long time later, I wrote a custom management command, and it would do this:
from myapp.models import MyModel
When I ran my custom command (python manage.py my_command) this would result in Python complaining that the module auth had no attribute models on the line declaring the ForeignKey in models.py.
To work around this problem, I changed my models.py to the more usual:
from django.contrib.auth.models import User
class MyModel(models.Model):
user = models.ForeignKey(User)
# ...
Can someone explain to me what I am missing? Is there something different in the environment when you run a management command? Or was I just doing it wrong the whole time? Thanks!
Edit: Following dmitko's hunch about circular imports, here are the imports used in my models.py file. I'm showing the original import of auth commented out, along with the only model that has a foreign key to the auth user model:
import datetime
from django.db import models
# from django.contrib import auth
from django.contrib.auth.models import User
class UserLastVisit(models.Model):
# user = models.ForeignKey(auth.models.User, unique=True)
# ^^^^^^^^^^^^^^^^
# after adding mgmt command, error occurred here; change to the line below
user = models.ForeignKey(User, unique=True)
last_visit = models.DateTimeField(db_index=True)
And here are the imports of the management command that uncovered the problem:
import datetime
from django.core.management.base import NoArgsCommand
from core.models import UserLastVisit, AnonLastVisit, Statistic
Was this setting up a circular import type situation?
If some random module ever imports module x.y.z, then a later person who imports just x.y will see a z in the x.y namespace.
The reason this happens is that import x.y.z is actually three import statements in one. It works something like this:
x = __internal_import('x')
x.y = __internal_import('x/y')
x.y.z = __internal_import('x/y/z')
Next time someone does __internal_import('x/y'), they'll get the same object, because python is smart enough not to import the same one twice. That object already has its z member assigned to the z module.
In your full app, probably you had a module that did import django.contrib.auth.models. But your minimal standalone program didn't import that module, so the name was never assigned.
(Note: there's no such thing as __internal_import. It's just an illustration. The real function has some other name that you would have to look up.)
I guess that if you do from django.contrib import auth that means you're importing auth package as a module and what it exports is driven by __init__.py in the auth folder:
>>> from django.contrib import auth
>>> dir(auth)
['BACKEND_SESSION_KEY', 'ImproperlyConfigured', 'REDIRECT_FIELD_NAME', 'SESSION_
KEY', '__builtins__', '__doc__', '__file__', '__name__', '__path__', 'authentica
te', 'datetime', 'get_backends', 'get_user', 'import_module', 'load_backend', 'l
ogin', 'logout']
You can check __init__.py in django\contrib\auth and see the same function list. When you import from django.contrib.auth.models import User that means that you're importing a submodule from the auth package and it works.
BTW. I was unable to use auth.models.User in any case - whether I run from console or from my django app.
It's hard to say exactly what's going on without seeing the new manage.py command that you added. However, I often see the " has no attribute " in cases with circular imports, and it's almost always fixed by changing the module-level imports to function- or class-level imports, as you did here. You might check if anything like that is going on here.

Categories