gpt4 book ai didi

python - 如何解决 django.core.exceptions.ImproperlyConfigured : Requested setting INSTALLED_APPS error?

转载 作者:行者123 更新时间:2023-12-05 01:07:55 26 4
gpt4 key购买 nike

当我尝试运行 python3 poppulate_first_app.py 文件时出现此错误(使用 Kali Linux 和 venv 与 django 3.1.7)。

错误...

Traceback (most recent call last):
File "/home/hadi/Documents/first_django_project/poppulate_first_app.py", line 4, in <module>
from first_app.models import *
File "/home/hadi/Documents/first_django_project/first_app/models.py", line 6, in <module>
class Topic(models.Model):
File "/home/hadi/Documents/first_django_project/venv/lib/python3.9/site-packages/django/db/models/base.py", line 108, in __new__
app_config = apps.get_containing_app_config(module)
File "/home/hadi/Documents/first_django_project/venv/lib/python3.9/site-packages/django/apps/registry.py", line 253, in get_containing_app_config
self.check_apps_ready()
File "/home/hadi/Documents/first_django_project/venv/lib/python3.9/site-packages/django/apps/registry.py", line 135, in check_apps_ready
settings.INSTALLED_APPS
File "/home/hadi/Documents/first_django_project/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__
self._setup(name)
File "/home/hadi/Documents/first_django_project/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 63, in _setup
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

我也尝试在 Windows 上运行它,但同样的错误,我也重新创建项目以防我错过设置或其他东西,我也尝试了这里发布的大多数答案,但没有一个对我有用。

这是我的 poppulate_first_app.py 代码:

import django
import random
from faker import Faker
from first_app.models import *
import os

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

django.setup()

# FAKE POP SCRIPT
fake_gen = Faker()
topics = ['Search', 'Social', 'Marketplace', 'News', 'Games']


def add_topic():
t = Topic.objects.get_or_create(top_name=random.choice(topics))[0]
t.save()
return t


def populate(n=5):
for entry in range(n):
# get the topic for the entry
top = add_topic()

# create the fake data for that entry
fake_url = fake_gen.url()
fake_date = fake_gen.date()
fake_name = fake_gen.company()

# create the new webpage entry
webpg = Webpage.objects.get_or_create(topic=top, url=fake_url, name=fake_name)[0]

# create a fake access record for that webpage
acc_rec = AccessRecord(namme=webpg, date=fake_date)


if __name__ == '__main__':
print('Populating script!')
populate(20)
print('Populating complete!')


这是我的 settings.py 代码:

"""
Django settings for first_django_project project.

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

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

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR = BASE_DIR / 'templates'
STATIC_DIR = BASE_DIR / 'static'

# 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 = 'f*7mcgl1l+4l@$qxf!xp*91l%*1^cl@@rp8&_m5upzr&4j_dqr'

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


ALLOWED_HOSTS = []

# Application definition

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

# import django
# django.setup()

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 = 'first_django_project.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATES_DIR, ],
'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 = 'first_django_project.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/'
STATICFILES_DIRS = [
STATIC_DIR,
]

这是我的 models.py 代码:

from django.db import models


# Create your models here.

class Topic(models.Model):
top_name = models.CharField(max_length=264, unique=True)

def __str__(self):
return self.top_name


class Webpage(models.Model):
topic = models.ForeignKey(Topic, on_delete=models.DO_NOTHING)
name = models.CharField(max_length=264, unique=True)
url = models.URLField(unique=True)

def __str__(self):
return self.name


class AccessRecord(models.Model):
name = models.ForeignKey(Webpage, on_delete=models.DO_NOTHING)
date = models.DateField()

def __str__(self):
return str(self.date)


这是我的 wsgi.py 代码:

"""
WSGI config for first_django_project 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.1/howto/deployment/wsgi/
"""

import os
from django.core.wsgi import get_wsgi_application

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

application = get_wsgi_application()

最佳答案

我只是移动

import os

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

django.setup()

from first_app.models import *

之前

关于python - 如何解决 django.core.exceptions.ImproperlyConfigured : Requested setting INSTALLED_APPS error?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66716375/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com