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 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

#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)
 

  • Frmt read ошибка пионер
  • Frm 92102 возникла ошибка сети
  • Frm 41211 ошибка интеграции сбой ssl при прогоне другого продукта
  • Friday the 13th the game ошибка при запуске
  • Friamat prime eco ошибка 34