I tried to execute
from django.db import models
but it gave the following error..
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.6/site-packages/Django-1.2.2-py2.6.egg/django/db/__init__.py",
line 14, in <module>
if not settings.DATABASES:
File "/Library/Python/2.6/site-packages/Django-1.2.2-py2.6.egg/django/utils/functional.py",
line 276, in __getattr__
self._setup()
File "/Library/Python/2.6/site-packages/Django-1.2.2-py2.6.egg/django/conf/__init__.py",
line 38, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is
undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable
DJANGO_SETTINGS_MODULE is undefined.
asked Jun 2, 2012 at 10:19
I’m assuming you are trying to do this import from the shell/terminal? If so you need to navigate into your Django project directory and type python manage.py shell
before executing your import.
answered Jun 2, 2012 at 10:33
solarticsolartic
4,1493 gold badges25 silver badges26 bronze badges
1
You need to add DJANGO_SETTINGS_MODULE in os.environ variables to specify which your settings file is. It seems you try to use django models outside a django app. What do you try to achieve? If you just want to test with python shell, you can use the Django shell from a Django app dir:
manage.py shell --settings=settings
UPDATE: solartic was faster
answered Jun 2, 2012 at 10:34
TishoTisho
8,1106 gold badges42 silver badges52 bronze badges
Django offers a powerful set of database modeling tools to help build enterprise-grade web applications. In some cases, application models need to reference each other dependently—this can lead to a circular import error. Fortunately, Django has an easy workaround.
Django is a robust Python-based web application framework with a powerful ORM model that supports Rapid Application Development (RAD). It does this, largely, through powerful abstractions of lower-level database programming. Yet another reason Python remains one of the most popular programming languages.
The Problem
In some cases, this abstraction makes logical errors tougher to diagnose—circular imports being one of them. Let’s say you have two models from different applications: Person
and Name
. Each Person
object gets a reference to a Name
object—which makes total sense given most people have names.
Each Name
object needs to easily access all Person
objects assigned that name. To make things easy, this is done via Django’s ManyToMany
field. To make this reference, you might import the Person
object from the People
app to define the association. Considering we’re doing a similar import with the People
model, that’s going to be an issue.
Below is the definition of the Person
class, defined in our app/people/models.py
file:
from django.db.models import Model, ForeignKey, CASCADE from names.models import Name class Person(Model): """ Our Person Model with a ForeignKey reference to the Name class. """ name = ForeignKey(Name, on_delete=CASCADE) ...
Below is the definition of the Name
class, defined in our app/names/models.py file:
from django.db.models import ManyToManyField, Model from people.models import Person class Name(Model): """ Object model for name, which references all Person Objects """ ... people = ManyToManyField(Person, related_name="person_name")
These classes, while a bit contrived for discussion’s sake, represent a co-dependency where each models.py
file requires the import of the others’. This is where the ImportError
is rooted. Without further consideration, we’ll get an error similar to the following:
ImportError: cannot import name 'Name' from partially initialized module 'names.models' (most likely due to a circular import) (C:userappnamesmodels.py)
Note: This is not a Django-specific error but rather a Python error (really a generic logical error) resulting from importing a file into a file that is importing the other. In other words; an infinite import loop.
The Solution
Fortunately, the great minds behind Django have provided a work-around for this common case. Through Django’s behind-the-scenes magic, one can avoid circular imports by using a string-based specification in model definitions. We just need to change the Name class to this:
from django.db.models import ManyToManyField, Model class Name(Model): """ Object model for name, which references all Person Objects """ ... people = ManyToManyField("people.Person", related_name="person_name")
Two things have happened:
- We removed the
from people.models import Person
statement (cause of the error); - We changed the
ManyToManyField
reference syntax to"people.Person"
instead ofPerson
.
This syntax is somewhat related to the forward reference update via PEP484. This update allows for functions and class definitions to reference non-declared functions and classes by using the quoted syntax.
Review
Django’s ORM provides developers with super-friendly APIs for dealing with basic-semi-complex database modeling. Throughout the years, Django’s developers have also made accommodations for complex database design as well as workarounds for common issues—the need for circular references being one. While these examples were a bit contrived, they illustrate how a little syntactic sugar goes a long way!
We love to use modules in Python and why not, they provide additional functionalities, better coding practice, and always create a proper structure while using. But many times unknowingly, we can run into python circular import problems if we accidentally have another file named as module’s name. As python prefers importing from the local current directory first and then from site-packages, it will create a circular import problem.
Generally, the Python Circular Import problem occurs when you accidentally name your working file the same as the module name and those modules depend on each other. This way the python opens the same file which causes a circular loop and eventually throws an error.
For example, when you name your file as random.py and try to import “from random import randint”, it’ll throw a circular import error (also termed as from partially initialized module).
In this post, we’ll have a look at all the causes and their solutions for circular import.
How Circular Import Is Identified?
Then a module calls an object within itself, circular import error is raised. Let’s consider an example where you are working on a ‘rea.py’ python file and you write a code as ‘from rea import x’. This will cause python to import the object x from the rea module.
This will cause a circular call within the code and it’ll throw an exception with an error mentioned as “ImportError: cannot import name ‘x’ from partially initialized module ‘rea’ (most likely due to a circular import) (/home/pythonpool/rea.py)”.
This exception is raised when you try to import any type of object. There are no exceptions.
Tip: Circular import is only raised when you import object from module. It is not raised when you try to import module itself. So, in above example, “import rea” will work just fine.
How to fix Python Circular Import?
There are several workarounds to solve the circular import problem. Each of these workarounds has its different use cases. Make sure you use the solution that suits best for your problem.
Conditional Import is also one of the ways by which you can handle such cases but does not try to use try-except blocks to fix circular imports as the core problem of importing variables still remain even if we ignore it.
Importing The Module Itself
There is a good workaround Python circular import error that you can import the module itself rather than importing object/function from the module. This way you can import and use all the objects and variables from the module.
Suppose, a module named module_name has function func_name, and you want to import it but it throws a circular error.
The easiest way to make this work is by importing the module_name itself. The following example will help you to understand it –
rea.py –
import rea x=1 if __name__ == '__main__': print(rea.x)
Even if you are calling the same module, it’ll work. Use these cases to fix the issues in flask and Django where the filenames can match the pre-defined module names.
Rename Your Working file
Sometimes, we can name our working file to module name without knowing its consequences (Even I did it many times :P). Renaming the file will work perfectly in such cases. For example, if you want to use the numpy module, you should avoid your working file naming numpy.py.
Here’s an example –
– numpy.py –
from numpy import array x = array([1, 2, 3])
ImportError: cannot import name 'array' from partially initialized module 'numpy' (most likely due to a circular import) (/home/pythonpool/numpy.py)
Now, rename our working file to a different name –
– pool_numpy.py –
from numpy import array x = array([1, 2, 3]) print(x)
[1 2 3]
Just as we avoid naming variables to built-in variables to avoid issues, you need to avoid naming your file to module name to avoid conflicts.
Avoid Circular Import Calls
Consider the following example –
– module1.py –
from module2 import func2 def func1(): func2()
– module2.py –
from module1 import func1 def func2(): func1()
Command to run –
python .module1.py
Traceback (most recent call last):
File "/home/pythonpool/module1.py", line 1, in <module>
from module2 import func2
File "/home/pythonpool/module2.py", line 1, in <module>
from module1 import func1
File "/home/pythonpool/module1.py", line 1, in <module>
from module2 import func2
ImportError: cannot import name 'func2' from partially initialized module 'module2' (most likely due to a circular import) (/home/pythonpool/module2.py)
The above example demonstrates a situation where you try to import a variable from module2 which is partially initialized (python doesn’t know that func2 even exists or not).
In such cases try to copy the required function/object to your working file.
In the above example, if you declare func2 itself in module1, it’ll not be of any problem.
Solve Circular Import Error In Django
Ever tried importing Django modules/classes in your Django project? You’ll definitely encounter a python circular import error once in such scenarios. If you try to implement the Django model manually by directly importing it, it’ll throw an error.
For example, you have your Django installed apps as follows –
INSTALLED_APPS = (
'app1',
)
And you want to use the structure of app1, you might import it directly in your python file considering its installed app. Something like this –
from app1.models import App1
Then most likely, you’ll encounter the python circular import error in your code. This is the incorrect way of importing a Model in your Django Application. Following is the correct way to do it –
For Django <=1.7:
from django.db.models import get_model MyModel = get_model('app1', 'App1')
For Django > 1.7:
from django.apps import apps apps.get_model('app1.App1')
This way the model ‘App1’ from app ‘app1’ will be imported into your Django application directly.
Solution for Python Circular Import Error In Flask
Similar to Django, flask also has circular import issues especially when you’re dealing with SQLAlchemy. If you try to use the database model of SQLAlchemy (declared in the main app file) in a different file, it’ll throw a circular import error.
Consider the following examples –
– app.py –
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__ name __) db = SQLAlchemy(app) from models import routes
– routes.py –
This is indeed a circular import as app.py called routes and routes call DB from app.py. To fix such issues we create a separate extension for a database where we initialize the SQLAlchemy database.
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()
This can be imported in app.py and models.py and used accordingly.
FAQs
Is there any python circular import detector?
Pycycle is a Github project which aims to detect circular import problems in your code. This tool has good command-line usage with multiple arguments usage.
Importing Static Variable at class level cause circular import?
Yes, if there is another import statement calling working module again, then it may cause circular import.
What causes circular import problems in __init__.py file?
__init__ file is responsible for importing and initializing packages. During this process, we always tend to import other modules from the package. So, if your other module calls back to another module that is yet to initialize in __init__, it’ll throw a circular import.
References
Python Import System: How searching of Modules works in Python.
Trending Python Articles
-
“Other Commands Don’t Work After on_message” in Discord Bots
●February 5, 2023
-
Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials
by Rahul Kumar Yadav●February 5, 2023
-
[Resolved] NameError: Name _mysql is Not Defined
by Rahul Kumar Yadav●February 5, 2023
-
Best Ways to Implement Regex New Line in Python
by Rahul Kumar Yadav●February 5, 2023
#python #django
#python #django
Вопрос:
Когда я пытаюсь перенести новое приложение на сервер, я получаю эту ошибку
Ошибка атрибута: модуль ‘django.db.models’ не имеет атрибута ‘Models’ — в терминале
Я использую PyCharm. Я очень новичок в Django и веб-разработке, поэтому любые советы помогут. Спасибо!
from django.db import models
# Create your models here.
class product(models.Model):
item = models.Textfiels()
description = models.Textfields()
price = models.Textfields()
Комментарии:
1. вы случайно не писали
models.Models
(с символомs
в конце) вместоmodels.Model
here?2. класс product (модели. Модель): элемент = модели. Textfiels() описание = модели. Textfields() цена = модели. Текстовые поля ()
3. у вас орфографическая ошибка:
models.Textfiels
но вам может потребоваться предоставить дополнительную информацию о вашей настройке, чтобы мы могли помочь диагностировать проблему. Какую версию django вы используете? Используете ли вы virtualenv? на что похож ваш макет проекта?4. django 2.0.7 и vitrualenv. Я буквально просто пытаюсь создать свое первое приложение. Я использовал sublime text, но предпочел pycharm, и вдруг он не работает. django.db неразрешен, я думаю, это может быть проблемой
5. Быстрый способ тестирования — активировать ваш virtualenv и попробовать оператор import в интерпретаторе python в вашем терминале: 1) source / path/ to/ your/ virtualenv / bin / activate и 2) запустить
python
в вашем терминале и попробовать 3)from django.db.models import Model
.
Ответ №1:
Такого класса нет django.db.models.TextFields
, но это работает для меня в любой последней версии :
from django.db import models
class product(models.Model):
item = models.TextFiel()
description = models.TextField()
price = models.TextField()
Вы допустили 2 опечатки: правильное имя TextField
и вы ввели Textfields
(Python чувствителен к регистру)
Я подозреваю, что вы неправильно настроили свой проект в PyCharm. При правильной настройке он показывает предупреждения о неправильно написанных именах (имена подчеркнуты красными точками с настройкой по умолчанию).
Комментарии:
1. Даже когда я исправляю написание или опечатки, у него та же проблема :/
2. Если вы ввели именно то, что в моем ответе, вы в правильном направлении. Но нам нужно больше контекста, чтобы дать реальный ответ на вашу проблему. т.Е. Вы создали virtualenv с совместимой версией Python? Вы пытались создать
product
модель в консоли django? Какова точная трассировка ? …
Ответ №2:
Есть еще один вариант этого вопроса, и он имеет вид:
AttributeError: module 'django.contrib.auth' has no attribute 'models'
Насколько я могу судить, это обычно вызвано конфликтующим импортом или неправильно импортированными файлами. Другой причиной могут быть изменения в обновлениях Django, но я не уверен в этом, поскольку я не нашел никакой документации, которая изменила бы этот аспект библиотеки Django.
Краткосрочное решение этой проблемы заключается в следующем:
from django.contrib.auth import models
class MyClass(models.User): """ """
Это позволит вам, по крайней мере, протестировать вашу команду runserver и веб-сайт в браузере по вашему выбору.
Я все еще пытаюсь найти какие-либо другие решения этой проблемы, которые могут быть исправлены для индивидуального импорта самого модуля ‘auth’.
На момент написания этой статьи я использую Django 2.2.6, тогда как Django 2.2.7 отсутствует, а 2.2.8 готовится к выпуску.
Ответ №3:
Я не уверен, что это решение, но когда у меня возникла эта проблема, это было потому, что в моем admin.py файл, который у меня был
from django.contrib import admin
from meetings.models import Meeting, Room
admin.site.register(Meeting, Room)
Но изменение его на решение проблемы
from django.contrib import admin
# Register your models here.
from meetings.models import Meeting, Room
admin.site.register(Meeting)
admin.site.register(Room)
Redzep 202 / 138 / 88 Регистрация: 21.12.2014 Сообщений: 369 |
||||||||||||
1 |
||||||||||||
15.03.2016, 11:55. Показов 3080. Ответов 3 Метки нет (Все метки)
Почему когда в любом месте подключаю models вылетает куча ошибок?
Traceback (most recent call last): Добавлено через 1 минуту
0 |
51 / 51 / 18 Регистрация: 03.12.2015 Сообщений: 167 |
|
15.03.2016, 17:19 |
2 |
Вы не забыли добавить app в installed_apps?
0 |
102 / 95 / 104 Регистрация: 29.11.2009 Сообщений: 407 |
|
29.03.2016, 13:56 |
3 |
http://pep8.ru/doc/pep8/
0 |
dieselwolf 0 / 0 / 0 Регистрация: 14.03.2016 Сообщений: 16 |
||||
29.03.2016, 14:15 |
4 |
|||
settings.py
0 |