【问题标题】:Faker() raised Django ImproperlyConfigured ErrorFaker() 引发 Django ImproperlyConfigured 错误
【发布时间】:2020-03-27 00:03:26
【问题描述】:

尝试使用 Faker 运行一些虚假数据,但现在已经尝试了 2 天来解决,但我无法解决。我需要一点帮助将不胜感激下面是代码和错误。我尝试了多种方法来尝试访问 Django 的设置模块但它不起作用我相信问题出在第 10 行 os.eniron ....etc

我正在使用 Windows 10、Sqlite、python 3.8.2 和 django 3 以及 venv 环境 python -m venv name

我已经打开了 django 管理员,我不知道现在会出现什么问题... 任何帮助将非常感激。谢谢!

test_first_app.py

import django
import os
import random

from faker import Faker

from first_app.models import AccessRecord, WebPage, Topic


os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings')
django.setup()

fake = Faker

topics = ['Search', 'Social', 'Marketplace']


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):
        top = add_topic()
        fake_url = fake.url()
        fake_date = fake.date()
        fake_name = fake.company()

        webpge = WebPage.objects.get_or_create(topic=top, url=fake_url, name=fake_name)[0]
        fkacc = AccessRecord.objects.get_create(name=webpge, date=fake_date)[0] # for some reason pycharm saying this variable is not used


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

models.py

from django.db import models


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

    def __str__(self):
        return self.top_name


class WebPage(models.Model):
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    name = models.CharField(max_length=150, unique=True)
    url = models.URLField(unique=True)

    def __str__(self):
        return self.name


class AccessRecord(models.Model):
    name = models.ForeignKey(WebPage, on_delete=models.CASCADE)
    date = models.DateField()

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

settings.py

"""
Django settings for first_project project.

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

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

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

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '-2gjsys0wt$&8sod%662o$=@2&s)+n_*8o$l)5=i3t#f(af+2y'

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

ALLOWED_HOSTS = []


# Application definition

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

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_project.urls'

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',
            ],
        },
    },
]

WSGI_APPLICATION = 'first_project.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

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

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    '/Django-Udemy/udemy/static/',
]

错误信息:

Traceback (most recent call last):
  File "test_first_app.py", line 7, in <module>
    from first_app.models import AccessRecord, WebPage, Topic
  File "D:\OneDrive\School\Django-Udemy\udemy\first_app\models.py", line
4, in <module>
    class Topic(models.Model):
  File "C:\Users\T\AppData\Local\Programs\Python\Python38-32\lib\site-pac
kages\django\db\models\base.py", line 107, in __new__
    app_config = apps.get_containing_app_config(module)
  File "C:\Users\T\AppData\Local\Programs\Python\Python38-32\lib\site-pac
kages\django\apps\registry.py", line 252, in get_containing_app_config
    self.check_apps_ready()
  File "C:\Users\T\AppData\Local\Programs\Python\Python38-32\lib\site-pac
kages\django\apps\registry.py", line 134, in check_apps_ready
    settings.INSTALLED_APPS
  File "C:\Users\T\AppData\Local\Programs\Python\Python38-32\lib\site-pac
kages\django\conf\__init__.py", line 76, in __getattr__
    self._setup(name)
  File "C:\Users\T\AppData\Local\Programs\Python\Python38-32\lib\site-pac
kages\django\conf\__init__.py", line 57, in _setup
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS,
but settings are not configured. You must either define the environment variable
e DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
.

【问题讨论】:

    标签: django python-3.x django-models django-views


    【解决方案1】:

    我看到上面的代码有几个问题:

    1. 你还没有实例化 Faker
    from faker import Faker
    fake = Faker()
    
    1. 我认为您试图在 django 应用程序之外访问 django。如果我的猜测是正确的,您尝试填充一些随机数据。为此,我认为您可以使用 django 自定义命令来做到这一点: https://docs.djangoproject.com/en/3.0/howto/custom-management-commands/

    【讨论】:

      【解决方案2】:

      我刚刚调试了我的 populate.py 文件,发现我在配置 Django 之前导入了 models.py,所以首先你需要设置环境,然后你需要设置 django,最后你可以在 populate.py 文件中导入模型。

      from faker import Faker
      import random
      import django
      import os
      
      # Configure settings for project
      # Need to run this before calling models from application!
      os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_model.settings') # this should be done first.
      
      # Import settings
      django.setup() # This needs to be done after you set the environ
      
      from first_app.models import Topic, WebPage, AccessRecord # At last you can import models in populate.py file
      # Now you are good to go for running this file
      
      fakegen = 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):
          '''
          Create N Entries of Dates Accessed
          '''
      
          for entry in range(N):
      
              # Get Topic for Entry
              top = add_topic()
      
              # Create Fake Data for entry
              fake_url = fakegen.url()
              fake_date = fakegen.date()
              fake_name = fakegen.company()
      
              # Create new Webpage Entry
              webpg = WebPage.objects.get_or_create(
                  topic=top, name=fake_name, url=fake_url,)[0]
      
              # Create Fake Access Record for that page
              # Could add more of these if you wanted...
              accRec = AccessRecord.objects.get_or_create(
                  name=webpg, date=fake_date)[0]
      
      
      if __name__ == '__main__':
          print("Populating the databases...Please Wait")
          populate(20)
          print('Populating Complete')
      

      【讨论】:

        猜你喜欢
        • 2011-08-30
        • 2016-05-28
        • 2022-07-12
        • 1970-01-01
        • 1970-01-01
        • 2017-11-17
        • 1970-01-01
        • 1970-01-01
        • 2020-12-09
        相关资源
        最近更新 更多