пытается запустить некоторые фальшивые данные с помощью Faker, но пытается уже 2 дня, чтобы решить, и я не могу. Мне нужна небольшая помощь, здесь будет высоко ценится ниже код и ошибка. Я пробовал несколько способов попробовать установочный модуль доступа Django, но он не работает, я считаю, что проблема в строке 10 os.eniron. ... et c
я работаю на Windows 10, Sqlite, python 3.8.2 и django 3 и среде venv python -m имя venv
у меня уже есть администратор 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
.