【发布时间】:2021-02-04 19:47:05
【问题描述】:
将rest_framework(pip install djangorestframework)添加到项目后发生此错误,但我不知道该框架中的原因。
我认为,错误日志对我来说信息量不够。如果需要共享任何文件,请告诉我。
注意:我是 django web api 的新手,所以您的任何建议都会很有价值。
提前谢谢你。
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run
autoreload.raise_last_exception()
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception
raise _exception[1]
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 357, in execute
autoreload.check_errors(django.setup)()
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\registry.py", line 91, in populate
app_config = AppConfig.create(entry)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\config.py", line 90, in create
module = import_module(entry)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'rest_framework'
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute
super().execute(*args, **options)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 371, in execute
output = self.handle(*args, **options)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 96, in handle
self.run(**options)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 103, in run
autoreload.run_with_reloader(self.inner_run, **options)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 618, in run_with_reloader
start_django(reloader, main_func, *args, **kwargs)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 603, in start_django
reloader.run(django_main_thread)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 318, in run
self.run_loop()
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 324, in run_loop
next(ticker)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 364, in tick
for filepath, mtime in self.snapshot_files():
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 380, in snapshot_files
for file in self.watched_files():
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 278, in watched_files
yield from iter_all_python_module_files()
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 105, in iter_all_python_module_files
return iter_modules_and_files(modules, frozenset(_error_files))
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 141, in iter_modules_and_files
resolved_path = path.resolve(strict=True).absolute()
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\pathlib.py", line 1172, in resolve
s = self._flavour.resolve(self, strict=strict)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\pathlib.py", line 200, in resolve
return self._ext_to_normal(_getfinalpathname(s))
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>'
这是 settings.py
"""
Django settings for backend project.
Generated by 'django-admin startproject' using Django 3.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
from datetime import date
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "9gr-03(+aq_#w-2j2*#wge200^#)&td$0w$q3vtonq1m^zdl63"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'rest_framework',
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"tsundoku",
]
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",
]
ROOT_URLCONF = "backend.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [
os.path.join(BASE_DIR, 'frontend/Tsundoku/src/'),
],
"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",
],
},
},
]
WSGI_APPLICATION = "backend.wsgi.application"
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
# MEDIA_URL this is for displaying image in browser ex. http://localhost:8000/images/d14f96e4b0e94973b151ea8097e28c01.jpg
MEDIA_URL = '/images/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
os.path.join(BASE_DIR, 'frontend/Tsundoku/src/static'),
)
# MEDIA_ROOT this is the directory where the images will be saved
MEDIA_ROOT = os.path.join(
BASE_DIR, f'static/images/')
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static/")
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
项目 -> urls.py
"""backend URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.conf import settings
from django.urls import path, include
from django.conf.urls.static import static
from django.views.generic import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('tsundoku.urls')),
path('', TemplateView.as_view(template_name='index.html'))
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
serializers.py
from django.contrib.auth.models import User, Group
from .model import Books
from rest_framework import serializers
class BooksSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Books
fields = ('name', 'writer', 'description')
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'groups']
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ['url', 'name']
models.py
from django.db import models
import uuid
from datetime import date
import static
from django.conf import settings
from django.contrib.auth.models import User, Group
# Create your models here.
class Categories(models.Model):
name = models.CharField(max_length=100, blank=False)
def __str__(self):
return self.name
class Writers(models.Model):
name = models.CharField(max_length=100, blank=False,
verbose_name="Writer name")
def __str__(self):
return self.name
def image_name(instance, filename):
new_name = uuid.uuid4().hex
filebase, extension = filename.split(".")
return f"{date.today().year}/{date.today().month}/{date.today().day}/{new_name}.{extension}"
class Books(models.Model):
name = models.CharField(
max_length=100, verbose_name="Book Name", blank=False)
description = models.CharField(
max_length=500, verbose_name="Book Description", blank=False
)
writer = models.ForeignKey(Writers, on_delete=models.CASCADE)
write_date = models.CharField(
max_length=4, verbose_name="Date", blank=False)
active = models.BooleanField(default="False", blank=False)
in_stock = models.PositiveIntegerField(blank=False)
category = models.ForeignKey(Categories, on_delete=models.CASCADE)
image = models.ImageField(
upload_to=image_name,
blank=True,
default="default_book.jpg",
)
pages = models.PositiveIntegerField(blank=True, default=0)
price = models.PositiveIntegerField(blank=False)
currency = models.CharField(default="AZN", max_length=10)
create_date = models.DateField(auto_now=False, auto_now_add=True)
last_edit_date = models.DateField(auto_now=True, auto_now_add=False)
def __str__(self):
return self.name
class Users(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
first_name = models.CharField(
verbose_name="First Name", max_length=25, blank=False)
last_name = models.CharField(
verbose_name="Last Name", max_length=25, blank=False)
email = models.EmailField(max_length=250, blank=False)
phone = models.CharField(max_length=20, blank=False)
active = models.BooleanField(default=False)
def __str__(self):
return self.first_name
class UserBook(models.Model):
user = models.ForeignKey(Users, on_delete=models.CASCADE)
book = models.ForeignKey(Books, on_delete=models.CASCADE)
def __str__(self):
return self.book.name
class UserAdress(models.Model):
user = models.ForeignKey(Users, on_delete=models.CASCADE)
country = models.CharField(max_length=50, blank=False)
city = models.CharField(max_length=50, blank=False)
postal_code = models.CharField(max_length=20, blank=False)
description = models.CharField(max_length=250, blank=True)
longitude = models.DecimalField(
max_digits=22, decimal_places=16, blank=True, null=True
)
latitude = models.DecimalField(
max_digits=22, decimal_places=16, blank=True, null=True
)
class Orders(models.Model):
user_adress = models.ForeignKey(UserAdress, on_delete=models.CASCADE)
book = models.ForeignKey(Books, on_delete=models.CASCADE)
djangorestframework 已经安装
$ pip install djangorestframework
Requirement already satisfied: djangorestframework in c:\users\fuadt\onedrive\desktop\python\tsundoku\backend\tsundoku_venv\lib\site-packages (3.12.2)
Requirement already satisfied: django>=2.2 in c:\users\fuadt\onedrive\desktop\python\tsundoku\backend\tsundoku_venv\lib\site-packages (from
djangorestframework) (3.1.5)
Requirement already satisfied: pytz in c:\users\fuadt\onedrive\desktop\python\tsundoku\backend\tsundoku_venv\lib\site-packages (from django>=2.2->djangorestframework) (2020.5)
Requirement already satisfied: sqlparse>=0.2.2 in c:\users\fuadt\onedrive\desktop\python\tsundoku\backend\tsundoku_venv\lib\site-packages (from django>=2.2->djangorestframework) (0.4.1)
Requirement already satisfied: asgiref<4,>=3.2.10 in c:\users\fuadt\onedrive\desktop\python\tsundoku\backend\tsundoku_venv\lib\site-packages (from django>=2.2->djangorestframework) (3.3.1)
(tsundoku_venv)
但它也给出了与 rest_framework 相关的错误
$ python manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 377, in execute
django.setup()
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\__init__.py", line
24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\registry.py",
line 91, in populate
app_config = AppConfig.create(entry)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\config.py", line 90, in create
module = import_module(entry)
File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in
_find_and_load
File "<frozen importlib._bootstrap>", line 973, in
_find_and_load_unlocked
ModuleNotFoundError: No module named 'rest_framework'
【问题讨论】:
-
阅读您正在安装的库的文档:django-rest-framework.org/#quickstart。您尚未将“rest_framework”添加到已安装的应用中。
-
很抱歉做出这样的假设。您只提到了运行 pip install 而没有其他任何内容。如果有人忘记将其添加到 INSTALLED_APPS,则该错误是相当标准的。如果我能帮助你,我稍后会多看一下
-
@ФуадТеймуров 你需要使用 pip3 安装 django-rest-framework,试试这个,
pip3 install djangorestframework -
如果我从自己的项目中卸载 DRF,但在 INSTALLED_APPS 中留下“rest_framework”,我会得到完全相同的错误。所以看起来你的 Django 可能在你的虚拟环境之外,这就是它找不到模块的原因?
-
@ФуадТеймуров 您可能已经在全局范围内安装了 rest 框架,而不是在 venv 上,反之亦然。全局尝试 pip freeze 并在 venv 中检查它是否安装在您想要的位置
标签: python django django-rest-framework django-serializer