IT story

Django 모델 "명시적인 app_label을 선언하지 않습니다"

hot-time 2020. 9. 7. 21:26
반응형

Django 모델 "명시적인 app_label을 선언하지 않습니다"


나는 재치의 끝이다. 수십 시간의 문제 해결을 마치고 아마 더 많은 시간을 들여 마침내 사업에 들어갔다고 생각했지만 다음과 같은 결과를 얻었습니다.

Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label 

웹에 이것에 대한 정보가 너무 적으며 해결책이 내 문제를 해결하지 못했습니다. 어떤 조언이라도 대단히 감사하겠습니다.

저는 Python 3.4와 Django 1.10을 사용하고 있습니다.

내 settings.py에서 :

INSTALLED_APPS = [
    'DeleteNote.apps.DeletenoteConfig',
    'LibrarySync.apps.LibrarysyncConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

내 apps.py 파일은 다음과 같습니다.

from django.apps import AppConfig


class DeletenoteConfig(AppConfig):
    name = 'DeleteNote'

from django.apps import AppConfig


class LibrarysyncConfig(AppConfig):
    name = 'LibrarySync'

설정 파일에 응용 프로그램 이름을 넣지 않았습니까? myAppNameConfig에 의해 apps.py에서 생성 된 기본 클래스입니다 .manage.py createapp의 myAppName의 명령. 여기서 myAppName 은 앱의 이름입니다.

settings.py

INSTALLED_APPS = [
'myAppName.apps.myAppNameConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

이렇게하면 설정 파일이 응용 프로그램을 호출 할 항목을 찾습니다. 다음 코드를 추가하여 apps.py 파일에서 나중에 표시되는 방식을 변경할 수 있습니다.

myAppName / apps.py

class myAppNameConfig(AppConfig):
    name = 'myAppName'
    verbose_name = 'A Much Better Name'

동일한 오류가 발생하고이 문제를 해결하는 방법을 모릅니다. django의 manage.py와 동일한 디렉토리에 init.py가 있다는 것을 알아 차리는 데 많은 시간이 걸렸습니다.

전에:

|-- myproject
  |-- __init__.py
  |-- manage.py
  |-- myproject
    |-- ...
  |-- app1
    |-- models.py
  |-- app2
    |-- models.py

후:

|-- myproject
  |-- manage.py
  |-- myproject
    |-- ...
  |-- app1
    |-- models.py
  |-- app2
    |-- models.py

"명시적인 app_label을 선언하지 않음"오류가 발생하는 것은 매우 혼란 스럽습니다. 그러나이 초기화 파일을 삭제하면 내 문제가 해결되었습니다.


나는 이것을 사용할 때 ./manage.py shell실수로 루트 프로젝트 수준 디렉토리에서 가져 왔습니다.

# don't do this
from project.someapp.someModule import something_using_a_model
# do this
from someapp.someModule import something_using_a_model

something_using_a_model()

PyCharm으로 테스트를 실행할 때 똑같은 오류가 발생했습니다. DJANGO_SETTINGS_MODULE환경 변수 를 명시 적으로 설정하여 수정했습니다 . PyCharm을 사용하는 경우 구성 편집 버튼을 누르고 환경 변수를 선택하십시오 .

변수를로 설정하면 your_project_name.settings문제가 해결됩니다.

PyCharm이 자체적으로 테스트를 실행하기 때문에이 오류가 발생하는 것 같습니다 manage.py.


나는 지금 바로 같은 문제가 있었다. 앱 이름에 네임 스페이스를 추가하여 내 문제를 해결했습니다. 누군가가 도움이되기를 바랍니다.

apps.py

from django.apps import AppConfig    

class SalesClientConfig(AppConfig):
        name = 'portal.sales_client'
        verbose_name = 'Sales Client'

Python3을 사용하는 멍청한 사람으로서 Django 오류 대신 가져 오기 오류 일 수 있음 알았습니다 .

잘못된:

from someModule import someClass

권리:

from .someModule import someClass

this happens a few days ago but I really can't reproduce it...I think only people new to Django may encounter this.here's what I remember:

try to register a model in admin.py:

from django.contrib import admin
from user import User
admin.site.register(User)

try to run server, error looks like this

some lines...
File "/path/to/admin.py" ,line 6
tell you there is an import error
some lines...
Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label

change user to .user ,problem solved


I got this error on importing models in tests, i.e. given this Django project structure:

|-- myproject
    |-- manage.py
    |-- myproject
    |-- myapp
        |-- models.py  # defines model: MyModel
        |-- tests
            |-- test_models.py

in file test_models.py I imported MyModel in this way:

from models import MyModel

The problem was fixed if it is imported in this way:

from myapp.models import MyModel

Hope this helps!

PS: Maybe this is a bit late, but I not found in others answers how to solve this problem in my code and I want to share my solution.


I got this error while trying to upgrade my Django Rest Framework app to DRF 3.6.3 and Django 1.11.1.

For anyone else in this situation, I found my solution in a GitHub issue, which was to unset the UNAUTHENTICATED_USER setting in the DRF settings:

# webapp/settings.py
...
REST_FRAMEWORK = {
    ...
    'UNAUTHENTICATED_USER': None
    ...
}

I ran into this error when I tried generating migrations for a single app which had existing malformed migrations due to a git merge. e.g.

manage.py makemigrations myapp

When I deleted it's migrations and then ran:

manage.py makemigrations

the error did not occur and the migrations generated successfully.


I just ran into this issue and figured out what was going wrong. Since no previous answer described the issue as it happened to me, I though I would post it for others:

  • the issue came from using python migrate.py startapp myApp from my project root folder, then move myApp to a child folder with mv myApp myFolderWithApps/.
  • I wrote myApp.models and ran python migrate.py makemigrations. All went well.
  • then I did the same with another app that was importing models from myApp. Kaboom! I ran into this error, while performing makemigrations. That was because I had to use myFolderWithApps.myApp to reference my app, but I had forgotten to update MyApp/apps.py. So I corrected myApp/apps.py, settings/INSTALLED_APPS and my import path in my second app.
  • but then the error kept happening: the reason was that I had migrations trying to import the models from myApp with the wrong path. I tried to correct the migration file, but I went at the point where it was easier to reset the DB and delete the migrations to start from scratch.

So to make a long story short: - the issue was initially coming from the wrong app name in apps.py of myApp, in settings and in the import path of my second app. - but it was not enough to correct the paths in these three places, as migrations had been created with imports referencing the wrong app name. Therefore, the same error kept happening while migrating (except this time from migrations).

So... check your migrations, and good luck!


I've got a similar error while building an API in Django rest_framework.

RuntimeError: Model class apps.core.models.University doesn't declare an explicit > app_label and isn't in an application in INSTALLED_APPS.

luke_aus's answer helped me by correcting my urls.py

from

from project.apps.views import SurgeryView

to

from apps.views import SurgeryView

In my case I got this error when porting code from Django 1.11.11 to Django 2.2. I was defining a custom FileSystemStorage derived class. In Django 1.11.11 I was having the following line in models.py:

from django.core.files.storage import Storage, DefaultStorage

and later in the file I had the class definition:

class MyFileStorage(FileSystemStorage):

However, in Django 2.2 I need to explicitly reference FileSystemStorage class when importing:

from django.core.files.storage import Storage, DefaultStorage, FileSystemStorage

and voilà!, the error dissapears.

Note, that everyone is reporting the last part of the error message spitted by Django server. However, if you scroll up you will find the reason in the middle of that error mambo-jambo.


in my case I was able to find a fix and by looking at the everyone else's code it may be the same issue.. I simply just had to add 'django.contrib.sites' to the list of installed apps in the settings.py file.

hope this helps someone. this is my first contribution to the coding community


I had this error today trying to run Django tests because I was using the shorthand from .models import * syntax in one of my files. The issue was that I had a file structure like so:

    apps/
      myapp/
        models/
          __init__.py
          foo.py
          bar.py

and in models/__init__.py I was importing my models using the shorthand syntax:

    from .foo import *
    from .bar import *

In my application I was importing models like so:

    from myapp.models import Foo, Bar

This caused the Django model doesn't declare an explicit app_label when running ./manage.py test.

To fix the problem, I had to explicitly import from the full path in models/__init__.py:

    from myapp.models.foo import *
    from myapp.models.bar import *

That took care of the error.

H/t https://medium.com/@michal.bock/fix-weird-exceptions-when-running-django-tests-f58def71b59a


In my case, this was happening because I used a relative module path in project-level urls.py, INSTALLED_APPS and apps.py instead of being rooted in the project root. i.e. absolute module paths throughout, rather than relative modules paths + hacks.

No matter how much I messed with the paths in INSTALLED_APPS and apps.py in my app, I couldn't get both runserver and pytest to work til all three of those were rooted in the project root.

Folder structure:

|-- manage.py
|-- config
    |-- settings.py
    |-- urls.py
|-- biz_portal
    |-- apps
        |-- portal
            |-- models.py
            |-- urls.py
            |-- views.py
            |-- apps.py

With the following, I could run manage.py runserver and gunicorn with wsgi and use portal app views without trouble, but pytest would error with ModuleNotFoundError: No module named 'apps' despite DJANGO_SETTINGS_MODULE being configured correctly.

config/settings.py:

INSTALLED_APPS = [
    ...
    "apps.portal.apps.PortalConfig",
]

biz_portal/apps/portal/apps.py:

class PortalConfig(AppConfig):
    name = 'apps.portal'

config/urls.py:

urlpatterns = [
    path('', include('apps.portal.urls')),
    ...
]

Changing the app reference in config/settings.py to biz_portal.apps.portal.apps.PortalConfig and PortalConfig.name to biz_portal.apps.portal allowed pytest to run (I don't have tests for portal views yet) but runserver would error with

RuntimeError: Model class apps.portal.models.Business doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS

Finally I grepped for apps.portal to see what's still using a relative path, and found that config/urls.py should also use biz_portal.apps.portal.urls.


TL;DR: Adding a blank __init__.py fixed the issue for me.

I got this error in PyCharm and realised that my settings file was not being imported at all. There was no obvious error telling me this, but when I put some nonsense code into the settings.py, it didn't cause an error.

I had settings.py inside a local_settings folder. However, I'd fogotten to include a __init__.py in the same folder to allow it to be imported. Once I'd added this, the error went away.


I received this error after I moved the SECRET_KEY to pull from an environment variable and forgot to set it when running the application. If you have something like this in your settings.py

SECRET_KEY = os.getenv('SECRET_KEY')

then make sure you are actually setting the environment variable.


Most probably you have dependent imports.

In my case I used a serializer class as a parameter in my model, and the serializer class was using this model: serializer_class = AccountSerializer

from ..api.serializers import AccountSerializer

class Account(AbstractBaseUser):
    serializer_class = AccountSerializer
    ...

And in the "serializers" file:

from ..models import Account

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = (
            'id', 'email', 'date_created', 'date_modified',
            'firstname', 'lastname', 'password', 'confirm_password')
    ...

I got this error today and ended up here after googling. None of the existing answers seem relevant to my situation. The only thing I needed to do was to import a model from my __init__.py file in the top level of an app. I had to move my imports into the functions using the model.

Django seems to have some weird code that can fail like this in so many different scenarios!


I got this error also today. The Message referenced to some specific app of my apps in INSTALLED_APPS. But in fact it had nothing to do with this specific App. I used a new virtual Environment and forgot to install some Libraries, that i used in this project. After i installed the additional Libraries, it worked.

참고URL : https://stackoverflow.com/questions/40206569/django-model-doesnt-declare-an-explicit-app-label

반응형