From django db import models ошибка

This is weird. I can’t find the error. I can’t run the server (or anything) cause I get an error:

ImportError: cannot import name Libro

So these are the models:

perfiles.models.py-

from django.db import models
from django.contrib.auth.models import User

from libros.models import Libro <- WEIRD ERROR ??¡?

class Perfil(models.Model):
    usuario = models.OneToOneField(User, null=True)
    actualmente_leyendo = models.ForeignKey(Libro, related_name="actualmente_leyendo")
    ...

libros.models.py —

from django.db import models

from perfiles.models import Perfil

    class Libro(models.Model):
        titulo = models.CharField(max_length=255, blank=True)
        autor = models.CharField(max_length=255, blank=True)
        imagen = models.CharField(max_length=255, blank=True)

So, both «libros» and «perfiles» are apps registered on my settings.py and , when I open a ´python manage.py shell´ and run ´from libros.models import Libro´, it works correctly and gives me

(InteractiveConsole)
>>> from libros.models import Libro
>>> Libro
<class 'libros.models.Libro'>

So, where could the error be? and why can the python shell import the model and the other model can’t? Any ideas will be helpfull. Thanks.

I keep receiving the error Could not import movies.views. Error was: No module named models

Here is my traceback:

    Environment:


    Request Method: GET
    Request URL: http://localhost:8000/movies/awesome-movie/

    Django Version: 1.3.1
    Python Version: 2.7.3
    Installed Applications:
    ['django.contrib.auth',
     'username_patch',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.sites',
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'django.contrib.admin',
     'django.contrib.flatpages',
     'south',
     'tagging',
     'tagging_autocomplete',
     'accounts',
     'movies',
     'tracking',
     'djcelery',
     'pagination']
    Installed Middleware:
    ('django.middleware.common.CommonMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.middleware.locale.LocaleMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
     'pagination.middleware.PaginationMiddleware')


    Traceback:
    File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
      101.                             request.path_info)
    File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
      252.                     sub_match = pattern.resolve(new_path)
    File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
      252.                     sub_match = pattern.resolve(new_path)
    File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
      158.             return ResolverMatch(self.callback, args, kwargs, self.name)
    File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/urlresolvers.py" in _get_callback
      167.             raise ViewDoesNotExist("Could not import %s. Error was: %s" % (mod_name, str(e)))

    Exception Type: ViewDoesNotExist at /movies/awesome-movie/
    Exception Value: Could not import movies.views. Error was: No module named models

I am not sure why I have this error. My code is as follows…

I have an django app called tracking and another called movies. I have a python file called tracking.py in the tracking app it consists of the following code:

filmlibrary/tracking/tracking.py

from movies.models import Movie
from tracking.models import MovieView

import os
import base64

def tracking_id(request):
    try:
        return request.session['tracking_id']
    except KeyError:
        request.session['tracking_id'] = base64.b64encode(os.urandom(36))
        return request.session['tracking_id']

def log_movie_view(request, movie):
    t_id = tracking_id(request)
    try:
        v = MovieView.objects.get(tracking_id=t_id, movie=movie)
        v.save()
    except MovieView.DoesNotExist:
        v = MovieView()
        v.movie = movie
        v.ip_address = request.META.get('REMOTE_ADDR')
        v.tracking_id = t_id
        v.user = None
        if request.user.is_authenticated():
            v.user = request.user
        v.save()

The above is pretty basic stuff. My views.py in my movies app uses the tracking.py file here:

filmlibrary/movies/views.py

@login_required
def movie_details(request, slug, template_name="movies/movie_detail.html"):
    movie = get_object_or_404(Movie, slug=slug)
    movie.tracking_id = tracking.tracking_id(request)
    movie.save()
    tracking.log_movie_view(request, movie)
    context = RequestContext(request, {'movie': movie })
    if movie:
        try:
            screener = movie.moviemedia_set.get(movie_type='screener')
            .... continued

UPDATE:

Here are the contents of filmlibrary/tracking/models.py

from django.db import models
from django.contrib.auth.models import User

from movies.models import Movie

class PageView(models.Model):
    class Meta:
        abstract = True

    date = models.DateTimeField(auto_now=True)
    ip_address = models.IPAddressField()
    user = models.ForeignKey(User, null=True)
    tracking_id = models.CharField(max_length=50, default='')

class MovieView(PageView):
    movie = models.ForeignKey(Movie)

The error appears to come from the import line from tracking.models import MovieView in the tracking.py file and I am not sure why. As soon as I comment out that line the error goes away but then of course I’ll have new errors about MovieView not existing as expected. I don’t see anything wrong with that import line in tracking.py.

Does anyone have any suggestions as to why I receive that error and how I can resolve this?

marazmiki: Спасибо за ответ. Есть две модели
модель Новостей и категориев. У новостя есть категория, у новости может быть одна категория у категории может быть много новостей. Цель при удаление категории удалять и новости которые были связаны с текущей категории.

from django.db import models
from news.models import New

class TourCategory(models.Model):
    name = models.CharField(max_length=200, verbose_name="Имя")

    def delete(self, using=None, keep_parents=False):
        news = New.objects.get(category_id=self.id)
        self.delete()
        news.delete()

Я новичек но думаю вы поняли логику.

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

The Recruit's user avatar

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

solartic's user avatar

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

Tisho's user avatar

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:

  1. We removed the from people.models import Person statement (cause of the error);
  2. We changed the ManyToManyField reference syntax to "people.Person" instead of Person.

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?

Python Circular Import Flowchart

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.

“Other Commands Don’t Work After on_message” in Discord Bots

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.

Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials

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

    “Other Commands Don’t Work After on_message” in Discord Bots

    February 5, 2023

  • Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials

    Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials

    by Rahul Kumar YadavFebruary 5, 2023

  • [Resolved] NameError: Name _mysql is Not Defined

    [Resolved] NameError: Name _mysql is Not Defined

    by Rahul Kumar YadavFebruary 5, 2023

  • Best Ways to Implement Regex New Line in Python

    Best Ways to Implement Regex New Line in Python

    by Rahul Kumar YadavFebruary 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 вылетает куча ошибок?

Python
1
from app_name.models import App_name
Python
1
2
3
4
5
6
7
8
9
from django.db import models
 
# Create your models here.
class App_name(models.Model):
    class Meta():
        db_table = "app_name"
    app_name_1 = models.CharField(max_length=100)
    app_name_2 = models.CharField(max_length=100)
    app_name_3 = models.TextField()

Traceback (most recent call last):
File «E:/PythonProjects/my_app/manage.py», line 6, in <module>
from app_name.models import App_name
File «E:PythonProjectsmy_appapp_namemodels.py», line 4, in <module>
class App_name(models.Model):
File «E:Pythonlibsite-packagesdjangodbmodelsbase.py», line 94, in __new__
app_config = apps.get_containing_app_config(module)
File «E:Pythonlibsite-packagesdjangoappsregistry.py», line 239, in get_containing_app_config
self.check_apps_ready()
File «E:Pythonlibsite-packagesdjangoappsregistry.py», line 124, in check_apps_ready
raise AppRegistryNotReady(«Apps aren’t loaded yet.»)
django.core.exceptions.AppRegistryNotReady: Apps aren’t loaded yet.

Добавлено через 1 минуту
Без этой строчки все работает нормально (пробовал подключить в разных модулях — везде ошибки):

Python
1
from app_name.models import App_name

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

Python
1
2
3
4
5
INSTALLED_APPS = [
    ...
    'App_name',
    ...
]

0

I keep receiving the error Could not import movies.views. Error was: No module named models

Here is my traceback:

    Environment:


    Request Method: GET
    Request URL: http://localhost:8000/movies/awesome-movie/

    Django Version: 1.3.1
    Python Version: 2.7.3
    Installed Applications:
    ['django.contrib.auth',
     'username_patch',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.sites',
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'django.contrib.admin',
     'django.contrib.flatpages',
     'south',
     'tagging',
     'tagging_autocomplete',
     'accounts',
     'movies',
     'tracking',
     'djcelery',
     'pagination']
    Installed Middleware:
    ('django.middleware.common.CommonMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.middleware.locale.LocaleMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
     'pagination.middleware.PaginationMiddleware')


    Traceback:
    File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
      101.                             request.path_info)
    File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
      252.                     sub_match = pattern.resolve(new_path)
    File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
      252.                     sub_match = pattern.resolve(new_path)
    File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
      158.             return ResolverMatch(self.callback, args, kwargs, self.name)
    File "/Users/jeff/Code/filmlibrary/lib/python2.7/site-packages/django/core/urlresolvers.py" in _get_callback
      167.             raise ViewDoesNotExist("Could not import %s. Error was: %s" % (mod_name, str(e)))

    Exception Type: ViewDoesNotExist at /movies/awesome-movie/
    Exception Value: Could not import movies.views. Error was: No module named models

I am not sure why I have this error. My code is as follows…

I have an django app called tracking and another called movies. I have a python file called tracking.py in the tracking app it consists of the following code:

filmlibrary/tracking/tracking.py

from movies.models import Movie
from tracking.models import MovieView

import os
import base64

def tracking_id(request):
    try:
        return request.session['tracking_id']
    except KeyError:
        request.session['tracking_id'] = base64.b64encode(os.urandom(36))
        return request.session['tracking_id']

def log_movie_view(request, movie):
    t_id = tracking_id(request)
    try:
        v = MovieView.objects.get(tracking_id=t_id, movie=movie)
        v.save()
    except MovieView.DoesNotExist:
        v = MovieView()
        v.movie = movie
        v.ip_address = request.META.get('REMOTE_ADDR')
        v.tracking_id = t_id
        v.user = None
        if request.user.is_authenticated():
            v.user = request.user
        v.save()

The above is pretty basic stuff. My views.py in my movies app uses the tracking.py file here:

filmlibrary/movies/views.py

@login_required
def movie_details(request, slug, template_name="movies/movie_detail.html"):
    movie = get_object_or_404(Movie, slug=slug)
    movie.tracking_id = tracking.tracking_id(request)
    movie.save()
    tracking.log_movie_view(request, movie)
    context = RequestContext(request, {'movie': movie })
    if movie:
        try:
            screener = movie.moviemedia_set.get(movie_type='screener')
            .... continued

UPDATE:

Here are the contents of filmlibrary/tracking/models.py

from django.db import models
from django.contrib.auth.models import User

from movies.models import Movie

class PageView(models.Model):
    class Meta:
        abstract = True

    date = models.DateTimeField(auto_now=True)
    ip_address = models.IPAddressField()
    user = models.ForeignKey(User, null=True)
    tracking_id = models.CharField(max_length=50, default='')

class MovieView(PageView):
    movie = models.ForeignKey(Movie)

The error appears to come from the import line from tracking.models import MovieView in the tracking.py file and I am not sure why. As soon as I comment out that line the error goes away but then of course I’ll have new errors about MovieView not existing as expected. I don’t see anything wrong with that import line in tracking.py.

Does anyone have any suggestions as to why I receive that error and how I can resolve this?

Пишу первое свое (в смысле — не по мотивам учебников) приложение.
До недавнего времени все шло хорошо. Но сейчас вылетает Internal server error. В консоли ошибка:

  File "c:Djangomrpetsviews.py", line 5, in <module>
from . models import Pets, Events
ImportError: cannot import name 'Pets'

Не могу понять, почему, раньше все работало и в views.py ничего во время появления ошибки не менялось (только дописывалась функция в models.py)

models.py с классом Pets, на который ругается сервер:

#coding: utf8
import datetime
from django.db import models
from django.utils import timezone
from django.contrib import admin
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from . import views
class Pets(models.Model):
	Gen = (
		('0', 'Неизвестно'),
		('1', 'Самец'),
		('2', 'Самка'))
	u_name = models.ForeignKey(User)
	pet_name = models.CharField('Имя питомца', max_length=20)
	species = models.ForeignKey(Species, on_delete=models.DO_NOTHING, 
		null = True, verbose_name = 'Вид животного', related_name = 'keepers')
	morph = models.CharField('Морфа',max_length=50, blank = True)
	gender = models.CharField('Пол',max_length=1, choices = Gen)
	birth_date = models.DateField('Дата рождения',null = True)
	fed_freq = models.DurationField('Частота кормления',null = True)
	pet_comment = models.TextField('Комментарий',blank = True)
	def get_absolute_url(self):
		return reverse(views.PetDetailView, kwargs={'pk': self.pk}) 
	class Meta(object):
		ordering = ['pet_name']
		verbose_name = 'Pet'
		verbose_name_plural = 'Pets'

views.py не вижу смысла приводить полностью, строка импорта, на которую ругается сервер, вот:

from . models import Pets, Events

Куда копать? Вообще ума не приложу, вроде все выглядит корректно.
Дайте наводку, плиз.

Я работаю над проектом с использованием django и использую программное обеспечение Visual Studio Code.

В моем каталоге «store» есть пакет python под названием «tiendaonline» и приложение под названием «gestionpedidos», где я пытаюсь создать таблицу (DDBB)

Проблема, которую я получаю, заключается в том, что я не могу создать таблицу, потому что когда я пытаюсь запустить «py manage.py makemigrations», я вижу msg «No changes detected». Также я вижу в окне под названием проблемы следующее сообщение: » Import «django.db.models» could not be resolved from source «

«.

Мой set.py выглядит следующим образом:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'gestionpedidos',
]

а моя модель такова:

from django.db import models

# Create your models here.
class Pedidos(models.Model):
    numero = models.IntegerField(max_length=100 )
    fecha = models.DateField(max_length=300 )
    entregado = models.BooleanField() 

class Clientes(models.Model):
    name = models.CharField(max_length=30 )
    direc = models.CharField(max_length=50 )
    Email = models.EmailField() 
    Tel = models.EmailField() 

class Articulos(models.Model):
    name = models.CharField(max_length=100 )
    seccion = models.CharField(max_length=300 )
    price = models.IntegerField() 

Я не знаю, что происходит. Он может дать мне адрес перехода, например «0001_init», но не работает.

Спасибо

сначала перезапустите код vs, а затем активируйте виртуальную среду, если вы ее используете. снова выполните makemigrations и мигрируйте, если изменений не обнаружено, удалите недавнюю миграцию и сделайте это снова

Добавили ли вы папку migrations в приложение gestionpedidos?

Если django не обнаруживает изменения, сделайте следующее
py manage.py makemigrations gestionpedidos чтобы искать изменения только в этом приложении. Я не уверен почему, но это срабатывало для меня бесчисленное количество раз в прошлом.

Вернуться на верх

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:

  1. We removed the from people.models import Person statement (cause of the error);
  2. We changed the ManyToManyField reference syntax to "people.Person" instead of Person.

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!

Redzep

202 / 138 / 88

Регистрация: 21.12.2014

Сообщений: 369

1

15.03.2016, 11:55. Показов 3051. Ответов 3

Метки нет (Все метки)


Почему когда в любом месте подключаю models вылетает куча ошибок?

Python
1
from app_name.models import App_name
Python
1
2
3
4
5
6
7
8
9
from django.db import models
 
# Create your models here.
class App_name(models.Model):
    class Meta():
        db_table = "app_name"
    app_name_1 = models.CharField(max_length=100)
    app_name_2 = models.CharField(max_length=100)
    app_name_3 = models.TextField()

Traceback (most recent call last):
File «E:/PythonProjects/my_app/manage.py», line 6, in <module>
from app_name.models import App_name
File «E:PythonProjectsmy_appapp_namemodels.py», line 4, in <module>
class App_name(models.Model):
File «E:Pythonlibsite-packagesdjangodbmodelsbase.py», line 94, in __new__
app_config = apps.get_containing_app_config(module)
File «E:Pythonlibsite-packagesdjangoappsregistry.py», line 239, in get_containing_app_config
self.check_apps_ready()
File «E:Pythonlibsite-packagesdjangoappsregistry.py», line 124, in check_apps_ready
raise AppRegistryNotReady(«Apps aren’t loaded yet.»)
django.core.exceptions.AppRegistryNotReady: Apps aren’t loaded yet.

Добавлено через 1 минуту
Без этой строчки все работает нормально (пробовал подключить в разных модулях — везде ошибки):

Python
1
from app_name.models import App_name

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

Python
1
2
3
4
5
INSTALLED_APPS = [
    ...
    'App_name',
    ...
]

0

I want to fetch data from an API and store it in DB. But the api url should not be hardcoded in view. So I have created api.py in which calling the url request as below:

class API(object):
def __init__(self, key, base_url=None):
    self._key = key
    self._base_url = base_url
def get_predictor(self):
    payload = {'key': self._key, 'results':'100'}
    response = requests.get(
    self._get_url(),
    data=payload,
    timeout=(3.1, 10))
    self._get_url_predictor()
def _get_url_predictor(self):
    return '/'.join([self._base_url, 'api', 'meter', 'feed.json'])

Then I have created a file predictor were I am passing parameter to url and fetching details from API as below:

import urllib,json
from django.conf import settings
from AppSerializer.models import EnergyOTAPI, PowerPrediction
from AppSerializer.meter.api import API
def update_api_predictor():
for meter in EnergyOTAPI.objects.all():
            get_api_predector_data(meter)
def get_api_predector_data(meter):
api = API (
    key=meter.key,
    base_url=settings.SOURCE_ENDPOINTS['url_api'][0]
)
endpoint = api.get_predictor()
serialized_data = urllib.request.urlopen(endpoint).read()
output = json.loads(serialized_data)
def _create_sp_power_prediction_from_api():
    created_at = output['channels'][0]['feeds'][0]['created_at']
    entry_id = output['channels'][0]['feeds'][0]['entry_id']
    value = output['channels'][0]['feeds'][0]['value']
    PowerPrediction.objects.create(created=created_at,
                                        entry=entry_id,
                                        value=value)

Then for those fields I created models, serializer, views and url as below.

MOdels:

from django.db import models
class EnergyOTAPI:
key = models.CharField(max_length=255)
class PowerPrediction:
created = models.DateField()
entry = models.IntegerField('max_length=500')
value = models.IntegerField('max_length=500')

Serializer:

from rest_framework import serializers

from AppSerializer.models import PowerPrediction

class PowerPredictonSerializer(serializers.HyperlinkedModelSerializer):
    source = serializers.ReadOnlyField(source='source.pk')
    class Meta:
        model = PowerPrediction
        fields = ('created',
                  'entry',
                  'value')

Views:

from rest_framework.decorators import api_view
from rest_framework import generics, permissions, viewsets
from rest_framework.reverse import reverse
from rest_framework.response import Response
from AppSerializer.models import PowerPrediction
from AppSerializer.serializer import PowerPredictonSerializer

@api_view(['GET'])
def api_root(request, format=None):
return Response({
    'locations': reverse('solar:location-list', request=request,      format=format),
 'sources': reverse('source-list', request=request, format=format)
})

class PowerPredictionList(generics.ListAPIView):
queryset = PowerPrediction.objects.all()
serializer_class = PowerPredictonSerializer
def perform_create(self, serializer):
    serializer.save(location=self.request.location)

class PowerPredictionDetail(generics.RetrieveDestroyAPIView):
queryset = PowerPrediction.objects.all()
serializer_class = PowerPredictonSerializer

Понравилась статья? Поделить с друзьями:
  • From datetime import datetime в чем ошибка
  • Friday the 13th the game ошибка подключения
  • Friday the 13th the game ошибка summercamp
  • Friamat prime eco ошибка 34
  • Freshtunes ошибка в названии альбома