trying to run some fake data using Faker but been trying for 2 days now to solve and i cant. i need a little help here would be much appreciated below is the code and the error.I've tried multiple way to try an access Django's setting module but its not working i believe problem is in line 10 os.eniron....etc
im working on Windows 10, Sqlite, python 3.8.2 and django 3 and venv enviroment python -m venv name
i have the django admin on already i do not know what would be the problem now...
any help would be much appreciated. Thank you!
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/',
]
Error message:
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
.
I saw several problem with the code above:
You haven't instantiated Faker
from faker import Faker
fake = Faker()
I think you tried to access django outside django apps. If my guess is correct you tried to populate some random data. For this purpose I think you can do it using django custom command :
https://docs.djangoproject.com/en/3.0/howto/custom-management-commands/
I just debug my populate.py file and found that i was importing the models.py before configuring Django so first you need to set environment then you need to setup django and at last you can import models in populate.py file.
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')
Related
app/
├─ management/
│ ├─ commands/
│ │ ├─ customcommand.py
myfunction.py
site/
├─ settings.py
Content of settings.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 4.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
# 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/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '****'
# 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',
'app'
]
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 = 'site.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 = 'site.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.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/4.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny'
]
}
Content of customcommand.py
from django.core.management.base import BaseCommand, CommandError
import time
import requests
class Command(BaseCommand):
help = 'Closes the specified poll for voting'
def handle(self, *args, **options):
print("execued the commands success!!")
start_time = time.time()
for number in range(1, 50):
url = f'https://pokeapi.co/api/v2/pokemon/{number}'
resp = requests.get(url)
pokemon = resp.json()
print(pokemon['name'])
print("--- %s seconds ---" % (time.time() - start_time))
Contents of myfunction.py
from django.core import management
def funcA():
management.call_command('customcommand')
funcA()
On calling myfunction.py from terminal it throws raise CommandError("Unknown command: %r" % command_name)
os.environ['DJANGO_SETTINGS_MODULE'] = 'site.settings'
Inside myfunction.py I have tried setting this, but it still doesn't work. Can someone help me out here, probably I am missing out on some important config
Try adding __init__.py to management/ and commands/ directories.
I have solved the issue by adding the django.setup() call, after configuring the environment variable.
Inside myfunction.py, the following changes should be made
from django.core import management
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'site.settings')
django.setup()
def funcA():
management.call_command('customcommand')
funcA()
django.setup() is essential to include because it registers your applications and commands defined in your settings in a standalone script which the manage.py or django-admin takes care usually
I am trying to use EEL + Django. i found this solution in this GitHub link.
I managed to make Django find the eel.js. but the issue it disconnect just after making WebSocket handshaking.
as below:-
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, content types, sessions.
Run 'python manage.py migrate' to apply them.
January 31, 2021 - 17:22:47
Django version 3.1.5, using settings 'demo.settings'
Starting ASGI/Channels version 3.0.0 development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
HTTP GET /example/operations 200 [0.03, 127.0.0.1:57173]
HTTP GET /eel/eel.js 200 [0.01, 127.0.0.1:57173]
Not Found: /favicon.ico
HTTP GET /favicon.ico 404 [0.01, 127.0.0.1:57173]
WebSocket HANDSHAKING /eel [127.0.0.1:57177]
Exception inside application: object.__init__() takes exactly one argument (the instance to initialize)
Traceback (most recent call last):
File "D:\Python Projects\V1830Center\venv\lib\site-packages\channels\routing.py", line 71, in __call__
return await application(scope, receive, send)
File "D:\Python Projects\V1830Center\venv\lib\site-packages\channels\routing.py", line 160, in __call__
send,
File "D:\Python Projects\V1830Center\venv\lib\site-packages\asgiref\compatibility.py", line 33, in new_application
instance = application(scope)
File "D:\Python Projects\V1830Center\venv\lib\site-packages\channels\generic\websocket.py", line 23, in __init__
super().__init__(*args, **kwargs)
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
WebSocket DISCONNECT /eel [127.0.0.1:57177]
Project Tree:
Settings.py
"""
Django settings for demo project.
Generated by 'django-admin startproject' using Django 3.2a1.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/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/dev/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-!d$idwr9=e0e82xi=78hjc0vhtfyh45r#)*(1#vt+dqzryips5'
# 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',
'channels',
'django_eel',
'example',
]
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 = 'demo.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 = 'demo.wsgi.application'
ASGI_APPLICATION = "demo.routing.application"
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/dev/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/dev/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/dev/howto/static-files/
STATIC_URL = 'example/assets/'
STATICFILES_DIRS=(
os.path.join(BASE_DIR,'example/templates/example/assets/'),
)
# Default primary key field type
# https://docs.djangoproject.com/en/dev/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
routing.py:
from channels.routing import ProtocolTypeRouter, URLRouter
from django.conf.urls import url
from django_eel.consumers import EelConsumer
application = ProtocolTypeRouter({
# (http->django views is added by default)
"websocket": URLRouter([
url(r"^eel$", EelConsumer), # do not alter this line
]),
})
I wanted this solution to be able to use API + EEL methods together. so if anyone can help me with this problem. Thanks
I found solution for this problem,
that i added .as_asgi() to the routing.py file.
from channels.routing import ProtocolTypeRouter, URLRouter
from django.conf.urls import url
from django_eel.consumers import EelConsumer
application = ProtocolTypeRouter({
# (http->django views is added by default)
"websocket": URLRouter([
url(r"^eel$", EelConsumer.as_asgi()), # do not alter this line
]),
})
I have had this issue before, but I've managed to find the circular import being referenced. I face it again, but I can't find the problem.
My project's name is 'sare', and my sare/urls.py looks like this:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('users/', include('users.urls', namespace='users')),
path('admin/', admin.site.urls),
]
And users/urls.py is this:
from django.urls import path
from .views import UsersTableView#, UserCreateView, UserUpdateView, UserDeleteView
app_name = 'users'
urlpatterns = [
path('table/', UsersTableView.as_view(), name='users_table'),
# path('create/', UserCreateView.as_view(), name='users_create'),
# path('update/<int:pk>', UserUpdateView.as_view(), name='users_update'),
# path('delete/<int:pk>', UserDeleteView.as_view(), name='users_delete'),
]
The only piece of code that is not commented in my views is the UsersTableView, that looks like this:
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from .models import CustomUser
from .tables import UsersTable
from .filters import UserFilter
from .form_helpers import UsersFilterFormHelper
from django.views.generic import CreateView, UpdateView, DeleteView
from .forms import UserForm
from django.urls import reverse_lazy, reverse
from django_tables2.export import ExportMixin
from django_tables2 import RequestConfig,SingleTableView,Table as TableBase
from django_filters import FilterSet
class InitUserMixin(object):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop("user", None)
super(InitUserMixin, self).__init__(*args, **kwargs)
class FilterUserMixin(InitUserMixin, FilterSet):
pass
class Table(InitUserMixin, TableBase):
pass
class PagedFilteredTableView(ExportMixin, SingleTableView):
filter_class = None
formhelper_class = None
context_filter_name = 'filter'
def get_queryset(self, **kwargs):
qs = super(PagedFilteredTableView, self).get_queryset()
self.filter = self.filter_class(self.request.GET, queryset=qs, user=self.request.user)
self.filter.form.helper = self.formhelper_class()
return self.filter.qs
def get_table(self, **kwargs):
table = super(PagedFilteredTableView, self).get_table(user=self.request.user)
RequestConfig(self.request, paginate={'page': self.kwargs.get('page', 1),
"per_page": self.paginate_by}).configure(table)
return table
def get_context_data(self, **kwargs):
context = super(PagedFilteredTableView, self).get_context_data(**kwargs)
context[self.context_filter_name] = self.filter
return context
class UsersTableView(LoginRequiredMixin,PagedFilteredTableView, UserPassesTestMixin):
model = CustomUser
table_class = UsersTable
template_name = 'users/users_table.html'
paginate_by = 10
filter_class = UserFilter
formhelper_class = UsersFilterFormHelper
def test_func(self):
if self.request.user.is_superuser:
return True
else:
return False
I've tried to comment everything in the view and just write pass, but it gives the same result.
I cannot see any circular import. Do you see anything wrong with this code, or something else I should check out?
Traceback (most recent call last):
File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\core\management\base.py", line 395, in check
include_deployment_checks=include_deployment_checks,
File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\core\management\base.py", line 382, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\urls\resolvers.py", line 406, in check
for pattern in self.url_patterns:
File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\urls\resolvers.py", line 596, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf 'sare.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
EDIT:
My settings.py is this:
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 = '^*5r6l%i-dubv_ur*p06d*rp#d#*dg#4z%&li8#f4ca=h9z-r*'
# 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',
'rest_framework',
'rest_framework.authtoken',
'sare',
'formats',
'users',
'crequest',
'django_tables2',
'django_filters',
#'allauth', # registration
#'allauth.account', # registration
#'allauth.socialaccount', # registration
]
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 = 'sare.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 = 'sare.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/'
AUTH_USER_MODEL = 'users.CustomUser'
Watch out for the MRO (method resolution order) in your view class UsersTableView(LoginRequiredMixin, PagedFilteredTableView, UserPassesTestMixin), the mixins should always be at the beginning of hierarchy to be taken into account.
Otherwise, to see what would be the circular import, we would need the content of the following files:
models.py
tables.py
filters.py
form_helpers.py
forms.py
Or you can try to debug it yourself:
simply launch a python interpreter in your project
import sare.urls or import sare.views
it should give a ImportError, a more precise clue as to where the circular import is
Are you importing UsersTableView properly and defined it? it seems your use case is pretty beginner level of Django so I suggest check the Django class-based views and URLs docs again and check your code accordingly.
I built a very simple Django application to try unit testing. I can run a test without any problem when not importing any Django model, like:
import os
from django.test import TestCase
class FirstTest(TestCase):
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testje.settings")
def test_First(self):
a = 1
self.assertEqual(1, a)
I'm running Django 2.0.1. Now when I'm trying to import a model like:
import os
from django.test import TestCase
from polls.models import Question
class FirstTest(TestCase):
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testje.settings")
def test_First(self):
a = 1
self.assertEqual(1, a)
it will fail with the following stack trace:
Testing started at 16:46 ...
C:\Users\martijnka\virtualenvs\Test\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.2\helpers\pycharm\_jb_unittest_runner.py" --path D:/martijnka/Downloads/testDjango/testje/polls/tests.py
Launching unittests with arguments python -m unittest D:/martijnka/Downloads/testDjango/testje/polls/tests.py in D:\martijnka\Downloads\testDjango\testje\polls
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.2\helpers\pycharm\_jb_unittest_runner.py", line 35, in
main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING)
File "c:\program files (x86)\python36-32\Lib\unittest\main.py", line 94, in __init__
self.parseArgs(argv)
File "c:\program files (x86)\python36-32\Lib\unittest\main.py", line 141, in parseArgs
self.createTests()
File "c:\program files (x86)\python36-32\Lib\unittest\main.py", line 148, in createTests
self.module)
File "c:\program files (x86)\python36-32\Lib\unittest\loader.py", line 219, in loadTestsFromNames
suites = [self.loadTestsFromName(name, module) for name in names]
File "c:\program files (x86)\python36-32\Lib\unittest\loader.py", line 219, in
suites = [self.loadTestsFromName(name, module) for name in names]
File "c:\program files (x86)\python36-32\Lib\unittest\loader.py", line 153, in loadTestsFromName
module = __import__(module_name)
File "D:\martijnka\Downloads\testDjango\testje\polls\tests.py", line 5, in
from polls.models import Question
File "D:\martijnka\Downloads\testDjango\testje\polls\models.py", line 9, in
class Question(models.Model):
File "C:\Users\martijnka\virtualenvs\Test\lib\site-packages\django\db\models\base.py", line 100, in __new__
app_config = apps.get_containing_app_config(module)
File "C:\Users\martijnka\virtualenvs\Test\lib\site-packages\django\apps\registry.py", line 244, in get_containing_app_config
self.check_apps_ready()
File "C:\Users\martijnka\virtualenvs\Test\lib\site-packages\django\apps\registry.py", line 127, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
Process finished with exit code 1
Empty test suite.
My settings looks like this:
"""
Django settings for testje project.
Generated by 'django-admin startproject' using Django 2.0.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.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/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '********************************'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
# Application definition
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'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 = 'testje.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 = 'testje.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.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/2.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/2.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/2.0/howto/static-files/
STATIC_URL = '/static/'
As you can see I'm running from PyCharm CE 9the latest version). I have been looking for answers and trying many things but so far without any luck. Any idea what I'm missing here (probably something very simple)?
I'm learning how to do web programming with Django framework and I got this error message when I try to create an instance of my Artist from my app models. I use Python 3.6 version and Django 1.11.4 version.
File "<stdin>", line 1, in <module>
File ".\app\models.py", line 9, in <module>
class Artist(models.Model):
File "C:\Users\kadjo\documents\visual studio 2015\Projects\DatabaseFun\DatabaseFun\env\lib\site-packages\django\db\models\base.py", line 110, in __new__
app_config = apps.get_containing_app_config(module)
File "C:\Users\kadjo\documents\visual studio 2015\Projects\DatabaseFun\DatabaseFun\env\lib\site-packages\django\apps\registry.py", line 247, in get_containing_app_config
self.check_apps_ready()
File "C:\Users\kadjo\documents\visual studio 2015\Projects\DatabaseFun\DatabaseFun\env\lib\site-packages\django\apps\registry.py", line 125, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
First add these lines on top of your settings.py file.
import django
django.setup()
And then if this doesn't work try to remove third-party applications from your installed apps list one-by-one. You can again load them later, It may be because of dependency on certain third-party apps.
this is my models package code
from django.db import models
# Create your models here.
class Artist(models.Model):
name = models.CharField("artist", max_length=50)
year_formed = models.PositiveIntegerField()
class Album(models.Model):
name = models.CharField("album", max_length=50)
artist = models.ForeignKey(Artist)
this is my app setting package code
"""
Django settings for DatabaseFun project.
Generated by 'django-admin startproject' using Django 1.9.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
import posixpath
# 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/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ec5ea5b6-ee2d-43db-8bb8-4562d88788ea'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'app',
# Add your apps here to enable them
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'DatabaseFun',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'DatabaseFun.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 = 'DatabaseFun.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/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/1.9/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/1.9/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/1.9/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['static']))
How are you running this code? If you are running it standalone, then you must use django.setup().
See: https://docs.djangoproject.com/en/1.11/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage