【问题标题】:ModuleNotFoundError: No module named ' django'ModuleNotFoundError: 没有名为“django”的模块
【发布时间】:2021-08-06 11:53:34
【问题描述】:

您好,我正在关注tutorial on YouTube,我使用邮递员将用户的请求发布到 api,就在他的教程之后。我发现了一个错误:

Internal Server Error: /
Traceback (most recent call last):
  File "E:\UsamaComputer\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "E:\UsamaComputer\env\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response
    response = response.render()
  File "E:\UsamaComputer\env\lib\site-packages\django\template\response.py", line 105, in render
    self.content = self.rendered_content
  File "E:\UsamaComputer\env\lib\site-packages\django\template\response.py", line 81, in rendered_content
    template = self.resolve_template(self.template_name)
  File "E:\UsamaComputer\env\lib\site-packages\django\template\response.py", line 63, in resolve_template
    return select_template(template, using=self.using)
  File "E:\UsamaComputer\env\lib\site-packages\django\template\loader.py", line 47, in select_template
    raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: index.html
[17/May/2021 12:38:41] "GET / HTTP/1.1" 500 80940
Internal Server Error: /favicon.ico
Traceback (most recent call last):
  File "E:\UsamaComputer\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "E:\UsamaComputer\env\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response
    response = response.render()
  File "E:\UsamaComputer\env\lib\site-packages\django\template\response.py", line 105, in render
    self.content = self.rendered_content
  File "E:\UsamaComputer\env\lib\site-packages\django\template\response.py", line 81, in rendered_content
    template = self.resolve_template(self.template_name)
  File "E:\UsamaComputer\env\lib\site-packages\django\template\response.py", line 63, in resolve_template
    return select_template(template, using=self.using)
  File "E:\UsamaComputer\env\lib\site-packages\django\template\loader.py", line 47, in select_template
    raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: index.html
[17/May/2021 12:38:41] "GET /favicon.ico HTTP/1.1" 500 80843
Bad Request: /auth/users/
[17/May/2021 12:38:45] "POST /auth/users/ HTTP/1.1" 400 58
Internal Server Error: /auth/users/
Traceback (most recent call last):
  File "E:\UsamaComputer\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "E:\UsamaComputer\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "E:\UsamaComputer\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "E:\UsamaComputer\env\lib\site-packages\rest_framework\viewsets.py", line 125, in view
    return self.dispatch(request, *args, **kwargs)
  File "E:\UsamaComputer\env\lib\site-packages\rest_framework\views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "E:\UsamaComputer\env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "E:\UsamaComputer\env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception      
    raise exc
  File "E:\UsamaComputer\env\lib\site-packages\rest_framework\views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "E:\UsamaComputer\env\lib\site-packages\rest_framework\mixins.py", line 19, in create
    self.perform_create(serializer)
  File "E:\UsamaComputer\env\lib\site-packages\djoser\views.py", line 144, in perform_create
    settings.EMAIL.activation(self.request, context).send(to)
  File "E:\UsamaComputer\env\lib\site-packages\templated_mail\mail.py", line 78, in send
    super(BaseEmailMessage, self).send(*args, **kwargs)
  File "E:\UsamaComputer\env\lib\site-packages\django\core\mail\message.py", line 284, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "E:\UsamaComputer\env\lib\site-packages\django\core\mail\message.py", line 241, in get_connection
    self.connection = get_connection(fail_silently=fail_silently)
  File "E:\UsamaComputer\env\lib\site-packages\django\core\mail\__init__.py", line 34, in get_connection
    klass = import_string(backend or settings.EMAIL_BACKEND)
  File "E:\UsamaComputer\env\lib\site-packages\django\utils\module_loading.py", line 17, in import_string
    module = import_module(module_path)
  File "c:\users\hussnain\appdata\local\programs\python\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 972, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked
ModuleNotFoundError: No module named ' django'
[17/May/2021 12:38:52] "POST /auth/users/ HTTP/1.1" 500 155458

我在谷歌上到处搜索并尽我所能解决这个错误,但一切都是徒劳的。当我在环境中运行pip freeze 时,它说我已经安装了django Django==3.2 当我尝试pip install django 它说requirement already satisfied 我也尝试在环境之外安装它,但同样的requirement already satisfied 我的WSGI.py 文件位于正确的地方。此外,这是我的文件 的屏幕截图。 这是我的 wsgi.py

"""
WSGI config for UsamaComputers project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'UsamaComputers.settings')

application = get_wsgi_application()

这是我的 settings.py 文件:

"""
Django settings for UsamaComputers project.

Generated by 'django-admin startproject' using Django 3.2.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""

from pathlib import Path
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.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-p=i3^g82t202a!nauup+(ysg--_mkpl35_#qgs_6pyj6gkx#)a'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

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


    'accounts',
    'djoser',

    "corsheaders",
    'rest_framework',
    'rest_framework.authtoken',
    'frontend',
     'rest_framework_simplejwt',

]

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',
    # thos is something i added and dont know what is that?
    'corsheaders.middleware.CorsMiddleware'
]

ROOT_URLCONF = 'UsamaComputers.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # os.path.join(BASE_DIR, '../frontend')
        'DIRS': [os.path.join(BASE_DIR, 'build')],
        '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 = 'UsamaComputers.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'shopingwebsite',
        'USER': 'postgres',
        'PASSWORD': '1234',
        'HOST': 'localhost'
    }
}
EMAIL_BACKEND = ' django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '94.mbbs.2@gmail.com'
EMAIL_HOST_PASSWORD = 'fparxqsqikbnqhvm'
EMAIL_USE_TLS = True

# Password validation
# https://docs.djangoproject.com/en/3.2/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.2/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.2/howto/static-files/

STATIC_URL = '/static/'

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'build/static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')


CORS_ORIGIN_ALLOW_ALL = True

REST_FRAMEWORK = {
   'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
      'rest_framework.authentication.TokenAuthentication',
    #    'rest_framework.authentication.SessionAuthentication',
   ),
   'DEFAULT_PERMISSION_CLASSES': (
         'rest_framework.permissions.IsAuthenticated'
   ),
}
SIMPLE_JWT = {
    'AUTH_HEADER_TYPES': ('JWT',),
}
DJOSER = {
    'SET_USERNAME_RETYPE': True,
    'LOGIN_FIELD': 'email',
    'USERNAME_CHANGED_EMAIL_CONFIRMATION': True,
    'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True,
    'SEND_CONFIRMATION_EMAIL': True,
    'SET_PASSWORD_RETYPE': True,
    'SET_USERNAME_RETYPE': True,
    'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}',
    'USERNAME_RESET_CONFIRM_URL': 'email/reset/confirm/{uid}/{token}',
    'ACTIVATION_URL': 'activate/{uid}/{token}',
    'SEND_ACTIVATION_EMAIL': True,
    'SETIALIZER': {
        'user_create':'accounts.serializers.UserCreateSerializer',
        'user':'accounts.serializers.UserCreateSerializer',
      
        'user_delete':'djoser.serializers.UserDeleteSerializer'

    }
}


AUTH_USER_MODEL = 'accounts.UserAccount'

这是邮递员的错误: 没有邮递员,它给了我同样的错误。 任何帮助将不胜感激 非常感谢。

【问题讨论】:

  • 你检查过你是否安装了 Django 版本吗? python3 -m django --version
  • pip 可能指向其他一些 python 安装。所以,你可能想运行python3 -m pip install django
  • 如果您使用的是 IDE,您是否检查过它是否在自己的虚拟环境中运行?
  • EMAIL_BACKEND = ' django.core.mail.backends.smtp.EmailBackend' 注意到 space 就在django.core 之前(' 之后)?这就是你的错误的原因。删除空间因此它应该是EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
  • 是的@schuhesindbequemer 它说 3.2 。是的,它正在环境中运行。我试过python -m pip install django1 它说要求已经满足了。

标签: python python-3.x django django-rest-framework pip


【解决方案1】:

@AbdulAziz 所说的错误出现在额外的空间中

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' 注意到 django.core 之前的空格(' 之后)?这就是你的错误的原因。删除空格,因此它应该是 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' -

【讨论】:

    猜你喜欢
    • 2019-03-08
    • 2019-11-28
    • 2018-11-03
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多