Skip to content

RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

django3.2 + python3.9 + djangorestframework3.14.0

前提是如果你创建的Django项目,使用其全部功能,即没有注释掉任何settings.py中的各种组件和中间件,就不会遇到这个报错。

我从别处找了个页面报错截图: 1832669319994015744.png

这个报错在使用drf框架时,如果你用的是纯净版的Django,也就是不启用Django内置的auth、admin这些组件,那么我们在settings配置文件中,就会做如下配置:

python
DEBUG = True

ALLOWED_HOSTS = ["*"]

# 注释掉相关的apps
INSTALLED_APPS = [
    # 'django.contrib.admin',
    # 'django.contrib.auth',
    # 'django.contrib.contenttypes',
    # 'django.contrib.sessions',
    # 'django.contrib.messages',
    'django.contrib.staticfiles',
    'api.apps.ApiConfig',
    'rest_framework'
]
# 注释掉相应的中间件
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    # 'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    # 'django.contrib.auth.middleware.AuthenticationMiddleware',
    # 'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

# 模板中也注释掉相应的配置
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                # 'django.contrib.auth.context_processors.auth',
                # 'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

然后总路由urls.py中也删除默认的admin:

python
# from django.contrib import admin
from django.urls import path

urlpatterns = [
    # path('admin/', admin.site.urls),
]

完事执行完默认的数据库迁移之后,写个视图类:

python
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers

from api import models
from utils.encrypt import get_md5


class LoginSerializer(serializers.Serializer):
	""" 登录序列化器,因为登录不涉及保存数据库,所以直接用 serializers.Serializer 进行字段校验即可"""
	mobile = serializers.CharField(required=True)
	password = serializers.CharField(required=True)
	
	def validated_password(self, value):
		return get_md5(value)
	


class LoginView(APIView):
	""" 登录视图类 """
	def post(self, request):
		print(request.data)
		ser = LoginSerializer(data=request.data)
		if not ser.is_valid():
			return Response(ser.errors)
		return Response(ser.data)

然后你去访问它,你会发现报错: 1832669320388280320.png 这是因为drf的APIView内部会走认证源码,相关代码导致的报错,怎么解决呢?就是在settings.py中配置上如下两个参数即可:

python
REST_FRAMEWORK = {
    "UNAUTHENTICATED_USER": None,
    "UNAUTHENTICATED_TOKEN": None,
}

然后,重启项目,就可以了。

ImportError:Could not import'user'for API setting'UNAuTHENTICATED_USER'.ImportError:user doesn't look like a module path.

报错过程:

1832669321378136064.png

解决办法:

1832669323257184256.png

django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': cannot import name 'parse_header' from 'django.http.multipartparser'

刚创建的项目,执行命令迁移时报错:

bash
(.venv) F:\virtue\draft>python manage.py makemigrations
Traceback (most recent call last):
  File "F:\virtue\draft\.venv\lib\site-packages\django\template\utils.py", line 69, in __getitem__
    return self._engines[alias]
KeyError: 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "F:\virtue\draft\.venv\lib\site-packages\django\template\backends\django.py", line 128, in get_package_libraries
    module = import_module(entry[1])
  File "D:\python39\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 850, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "F:\virtue\draft\.venv\lib\site-packages\rest_framework\templatetags\rest_framework.py", line 12, in <module>
    from rest_framework.renderers import HTMLFormRenderer
  File "F:\virtue\draft\.venv\lib\site-packages\rest_framework\renderers.py", line 17, in <module>
    from django.http.multipartparser import parse_header
ImportError: cannot import name 'parse_header' from 'django.http.multipartparser' (F:\virtue\draft\.venv\lib\site-packages\django\http\multipartparser.py)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "F:\virtue\draft\manage.py", line 22, in <module>
    main()
  File "F:\virtue\draft\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "F:\virtue\draft\.venv\lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line
    utility.execute()
  File "F:\virtue\draft\.venv\lib\site-packages\django\core\management\__init__.py", line 436, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "F:\virtue\draft\.venv\lib\site-packages\django\core\management\base.py", line 412, in run_from_argv
    self.execute(*args, **cmd_options)
  File "F:\virtue\draft\.venv\lib\site-packages\django\core\management\base.py", line 453, in execute
    self.check()
  File "F:\virtue\draft\.venv\lib\site-packages\django\core\management\base.py", line 485, in check
    all_issues = checks.run_checks(
  File "F:\virtue\draft\.venv\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "F:\virtue\draft\.venv\lib\site-packages\django\contrib\admin\checks.py", line 78, in check_dependencies
    for engine in engines.all():
  File "F:\virtue\draft\.venv\lib\site-packages\django\template\utils.py", line 94, in all
    return [self[alias] for alias in self]
  File "F:\virtue\draft\.venv\lib\site-packages\django\template\utils.py", line 94, in <listcomp>
    return [self[alias] for alias in self]
  File "F:\virtue\draft\.venv\lib\site-packages\django\template\utils.py", line 85, in __getitem__
    engine = engine_cls(params)
  File "F:\virtue\draft\.venv\lib\site-packages\django\template\backends\django.py", line 24, in __init__
    options["libraries"] = self.get_templatetag_libraries(libraries)
  File "F:\virtue\draft\.venv\lib\site-packages\django\template\backends\django.py", line 42, in get_templatetag_libraries
    libraries = get_installed_libraries()
  File "F:\virtue\draft\.venv\lib\site-packages\django\template\backends\django.py", line 116, in get_installed_libraries
    return {
  File "F:\virtue\draft\.venv\lib\site-packages\django\template\backends\django.py", line 116, in <dictcomp>
    return {
  File "F:\virtue\draft\.venv\lib\site-packages\django\template\backends\django.py", line 105, in get_template_tag_modules
    for name in get_package_libraries(pkg):
  File "F:\virtue\draft\.venv\lib\site-packages\django\template\backends\django.py", line 130, in get_package_libraries
    raise InvalidTemplateLibrary(
django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': cannot import
 name 'parse_header' from 'django.http.multipartparser' (F:\virtue\draft\.venv\lib\site-packages\django\http\multipartparser.py)

环境:

bash
(.venv) F:\virtue\draft>pip list
Package             Version
------------------- -------
asgiref             3.8.1
Django              4.2.14
django-filter       24.2
djangorestframework 3.12.4
pip                 24.1.2
PyMySQL             1.1.1
pytz                2024.1
setuptools          70.2.0
sqlparse            0.5.0
typing_extensions   4.12.2
tzdata              2024.1

(.venv) F:\virtue\draft>python -V
Python 3.9.9

解决思路是djangorestframework版本太低,升级版本.

bash
pip install djangorestframework --upgrade

然后就好了.

参考:https://www.cnblogs.com/guo126/p/17601497.html