TangoWithDjango | 5.8 Creating a Population Script | Import Error - django

I'm currently following http://www.tangowithdjango.com/book/chapters/models.html .
On section 5.8 when I execute "python manage.py populate_rango.py" I got this error:
E:\PythonCode\django1\tango_with_django>python populate_rango.py
Starting Rango population script...
Traceback (most recent call last):
File "populate_rango.py", line 61, in <module>
from rango.models import Category, Page
File "E:\PythonCode\django1\tango_with_django\rango\models.py", line 1, in <module>
from django.db import models
File "C:\python27\lib\site-packages\django\db\models\__init__.py", line 5, in <module>
from django.db.models.query import Q
File "C:\python27\lib\site-packages\django\db\models\query.py", line 17, in <m
odule>
from django.db.models.deletion import Collector
File "C:\python27\lib\site-packages\django\db\models\deletion.py", line 4, in
<module>
from django.db.models import signals, sql
File "C:\python27\lib\site-packages\django\db\models\sql\__init__.py", line 4,
in <module>
from django.db.models.sql.subqueries import *
File "C:\python27\lib\site-packages\django\db\models\sql\subqueries.py", line
12, in <module>
from django.db.models.sql.query import Query
File "C:\python27\lib\site-packages\django\db\models\sql\query.py", line 22, i
n <module>
from django.db.models.sql import aggregates as base_aggregates_module
File "C:\python27\lib\site-packages\django\db\models\sql\aggregates.py", line
9, in <module>
ordinal_aggregate_field = IntegerField()
File "C:\python27\lib\site-packages\django\db\models\fields\__init__.py", line
116, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "C:\python27\lib\site-packages\django\conf\__init__.py", line 54, in __ge
tattr__
self._setup(name)
File "C:\python27\lib\site-packages\django\conf\__init__.py", line 49, in _set
up
self._wrapped = Settings(settings_module)
File "C:\python27\lib\site-packages\django\conf\__init__.py", line 132, in __i
nit__
% (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'tango_with_django_project.settings' (Is
it on sys.path? Is there an import error in the settings file?): No module named
tango_with_django_project.settings
Here is the files and directory location E:\PythonCode\django1\tango_with_django>
- manage.py
- populate_rango.py
- tango_with_django [directory]
---- settings.py
---- urls.py
- rango [directory]
---- models.py
models.py
from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
def __unicode__(self):
return self.name
class Page(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=128)
url = models.URLField()
views = models.IntegerField(default=0)
def __unicode__(self):
return self.title
populate_rango.py
import os
def populate():
python_cat = add_cat('Python')
add_page(cat=python_cat,
title="Official Python Tutorial",
url="http://docs.python.org/2/tutorial/")
add_page(cat=python_cat,
title="How to Think like a Computer Scientist",
url="http://www.greenteapress.com/thinkpython/")
add_page(cat=python_cat,
title="Learn Python in 10 Minutes",
url="http://www.korokithakis.net/tutorials/python/")
django_cat = add_cat("Django")
add_page(cat=django_cat,
title="Official Django Tutorial",
url="https://docs.djangoproject.com/en/1.5/intro/tutorial01/")
add_page(cat=django_cat,
title="Django Rocks",
url="http://www.djangorocks.com/")
add_page(cat=django_cat,
title="How to Tango with Django",
url="http://www.tangowithdjango.com/")
frame_cat = add_cat("Other Frameworks")
add_page(cat=frame_cat,
title="Bottle",
url="http://bottlepy.org/docs/dev/")
add_page(cat=frame_cat,
title="Flask",
url="http://flask.pocoo.org")
# Print out what we have added to the user.
for c in Category.objects.all():
for p in Page.objects.filter(category=c):
print "- {0} - {1}".format(str(c), str(p))
def add_page(cat, title, url, views=0):
p = Page.objects.get_or_create(category=cat, title=title, url=url, views=views)[0]
p.save()
return p
def add_cat(name):
c = Category.objects.get_or_create(name=name)[0]
c.save()
return c
# Start execution here!
if __name__ == '__main__':
print "Starting Rango population script..."
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings')
from rango.models import Category, Page
populate()
settings.py
"""
Django settings for tango_with_django project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
print BASE_DIR
SETTINGS_DIR = os.path.dirname(__file__)
PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir)
PROJECT_PATH = os.path.abspath(PROJECT_PATH)
TEMPLATE_PATH = os.path.join(PROJECT_PATH, 'templates')
TEMPLATE_DIRS = (
TEMPLATE_PATH,
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
DATABASE_PATH = os.path.join(PROJECT_PATH, 'rango.db')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'd!bvy8spg0ij7ok6o9%07*on&$1w#pxm=3+3lazxl#6s=h$yn&'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'rango',
)
MIDDLEWARE_CLASSES = (
'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 = 'tango_with_django.urls'
WSGI_APPLICATION = 'tango_with_django.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': DATABASE_PATH,
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/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.6/howto/static-files/
STATIC_PATH = os.path.join(PROJECT_PATH,'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
STATIC_PATH,
)

Your default path for the settings module is incorrect. You have tango_with_django_project.settings where your directory is tango_with_django.settings.
Thus, change the third to last line in your populate_rango.py file:
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django.settings')

Related

Getting error when trying to run to server with Channels

I'm having a problem running python manage.py runserver, to better exemplify, see my code inspired by the book Django 3 by Example.
settings.py:
"""
Django settings for educa 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
# 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 = 'XXX'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'channels',
'courses.apps.CoursesConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'students.apps.StudentsConfig',
'embed_video',
'debug_toolbar',
'redisboard',
'chat.apps.ChatConfig',
]
MIDDLEWARE = [
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
# 'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.cache.FetchFromCacheMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'educa.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',
],
},
},
]
ASGI_APPLICATION = 'educa.routing.application'
WSGI_APPLICATION = 'educa.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 = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
MEDIA_URL = 'media/'
MEDIA_ROOT = BASE_DIR / 'media'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
from django.urls import reverse_lazy
LOGIN_REDIRECT_URL = reverse_lazy('student_course_list')
'''CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.redis.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379',
}
}
CACHE_MIDDLEWARE_ALIAS = 'default'
CACHE_MIDDLEWARE_SECONDS = 60 * 15 # 15 minutes
CACHE_MIDDLEWARE_KEY_PREFIX = 'educa'
INTERNAL_IPS = [
'127.0.0.1',
]
'''
project/urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from courses.views import CourseListView
urlpatterns = [
path('accounts/login/', auth_views.LoginView.as_view(),
name='login'),
path('accounts/logout/', auth_views.LogoutView.as_view(),
name='logout'),
path('admin/', admin.site.urls),
path('course/', include('courses.urls')),
path('', CourseListView.as_view(), name='course_list'),
path('students/', include('students.urls')),
path('__debug__/', include('debug_toolbar.urls')),
path('chat/', include('chat.urls', namespace='chat')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
chat/views.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseForbidden
from django.contrib.auth.decorators import login_required
#login_required
def course_chat_room(request, course_id):
try:
# retrieve course with given id joined by the current user
course = request.user.courses_joined.get(id=course_id)
except:
# user is not a student of the course or course does not exist
return HttpResponseForbidden()
return render(request, 'chat/room.html', {'course': course})
chat/urls.py:
from django.urls import path
from . import views
app_name = 'chat'
urlpatterns = [
path('room/<int:course_id>/', views.course_chat_room,
name='course_chat_room'),
]
chat/consumers.py:
import json
from channels.generic.websocket import AsyncWebsocketConsumer
from asgiref.sync import async_to_sync
from django.utils import timezone
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.user = self.scope['user']
self.id = self.scope['url_route']['kwargs']['course_id']
self.room_group_name = 'chat_%s' % self.id
# join room group
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
# accept connection
await self.accept()
async def disconnect(self, close_code):
# leave room group
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
# receive message from WebSocket
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
now = timezone.now()
# send message to room group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message,
'user': self.user.username,
'datetime': now.isoformat(),
}
)
# receive message from room group
async def chat_message(self, event):
# send message to WebSocket
await self.send(text_data=json.dumps(event))
chat/routing.py:
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/chat/room/(?P<course_id>\d+)/$', consumers.
ChatConsumer),
]
project/routing.py:
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import chat.routing
application = ProtocolTypeRouter({
'websocket': AuthMiddlewareStack(
URLRouter(
chat.routing.websocket_urlpatterns
)
),
})
ERROR:
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
October 27, 2022 - 15:50:38
Django version 4.1.2, using settings 'educa.settings'
Starting ASGI/Channels version 2.4.0 development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\Sagittarius Infiny A\Desktop\educa2\env\lib\site-packages\channels\routing.py", line 29, in get_default_application
module = importlib.import_module(path)
File "C:\Users\Sagittarius Infiny A\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:\Users\Sagittarius Infiny A\Desktop\educa2\educa\routing.py", line 1, in <module>
from channels.auth import AuthMiddlewareStack
File "C:\Users\Sagittarius Infiny A\Desktop\educa2\env\lib\site-packages\channels\auth.py", line 15, in <module>
from django.utils.translation import LANGUAGE_SESSION_KEY
ImportError: cannot import name 'LANGUAGE_SESSION_KEY' from 'django.utils.translation' (C:\Users\Sagittarius Infiny A\Desktop\educa2\env\lib\site-packages\django\utils\translation\__init__.py)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Sagittarius Infiny A\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner
self.run()
File "C:\Users\Sagittarius Infiny A\AppData\Local\Programs\Python\Python310\lib\threading.py", line 953, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Sagittarius Infiny A\Desktop\educa2\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "C:\Users\Sagittarius Infiny A\Desktop\educa2\env\lib\site-packages\channels\management\commands\runserver.py", line 101, in inner_run
application=self.get_application(options),
File "C:\Users\Sagittarius Infiny A\Desktop\educa2\env\lib\site-packages\channels\management\commands\runserver.py", line 126, in get_application
return StaticFilesWrapper(get_default_application())
File "C:\Users\Sagittarius Infiny A\Desktop\educa2\env\lib\site-packages\channels\routing.py", line 31, in get_default_application
raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'educa.routing'
When trying the interactive module and trying to import the application from the project's routing.py, I get this error.
$ python manage.py shell
>> from educa.routing import application
Traceback (most recent call last): File "<console>", line 1, in <module>
File "C:\Users\Sagittarius Infiny A\Desktop\educa2\educa\routing.py", line 1, in <module>
from channels.auth import AuthMiddlewareStack
File "C:\Users\Sagittarius Infiny A\Desktop\educa2\env\lib\site-packages\channels\auth.py", line 15, in <module>
from django.utils.translation import LANGUAGE_SESSION_KEY
ImportError: cannot import name 'LANGUAGE_SESSION_KEY' from 'django.utils.translation' (C:\Users\Sagittarius Infiny A\Desktop\educa2\env\lib\site-packages\django\utils\translation\__init__.py)

Why do I get 'ImproperlyConfigured' exception, implying circular imports?

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.

Faker() raised Django ImproperlyConfigured Error

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')

Django 1.8.1 : A server error occurred. Please contact the administrator

I was working with django-1.8.1 and everything was good but when I tried again to run my server with command bellow, I get some errors :
command : python manage.py runserver
errors appeared in command-line :
> Traceback (most recent call last):
File "C:\Python34\lib\wsgiref\handlers.py", line 137, in run
self.result = application(self.environ, self.start_response)
File "C:\Python34\lib\site-packages\django\contrib\staticfiles\handlers.py", l
ine 63, in __call__
return self.application(environ, start_response)
File "C:\Python34\lib\site-packages\django\core\handlers\wsgi.py", line 170, i
n __call__
self.load_middleware()
File "C:\Python34\lib\site-packages\django\core\handlers\base.py", line 50, in
load_middleware
mw_class = import_string(middleware_path)
File "C:\Python34\lib\site-packages\django\utils\module_loading.py", line 24,
in import_string
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])
File "C:\Python34\lib\site-packages\django\utils\six.py", line 658, in reraise
>
> raise value.with_traceback(tb) File "C:\Python34\lib\site-packages\django\utils\module_loading.py", line
> 21, in import_string
> module_path, class_name = dotted_path.rsplit('.', 1) ImportError: polls doesn't look like a module path [24/Apr/2015 21:50:25]"GET /
> HTTP/1.1" 500 59
error appeared in browser :
A server error occurred. Please contact the administrator.
Also, I searched the web for this issue and I found something but they were not working for me.
This is my settings.py : `
"""
Django settings for havij project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
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.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '9va4(dd_pf#!(2-efc-ipiz#7fgb8y!d(=5gdmie0cces*9lih'
# 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',
'polls' ,
)
MIDDLEWARE_CLASSES = (
'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',
'django.middleware.security.SecurityMiddleware',
'polls',
)
ROOT_URLCONF = 'havij.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 = 'havij.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/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.8/howto/static-files/
STATIC_URL = '/static/'
`
And here is the urls.py :
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
# Examples:
# url(r'^$', 'havij.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
Thanks for your answering.
You've put your app name, polls, in MIDDLEWARE_CLASSES. It should only go in INSTALLED_APPs.
In other Django version (1.7) can be for 'django.middleware.security.SecurityMiddleware', in MIDDLEWARE_CLASSES.
try :
python manage.py migrate
it will create all tables for "admin"

Django ImportError: cannot import name ForumProfile

I use virtualenv for django.
And run python manage.py runserver at cmd.
In this site, the questions like importError most of them didn't be
solved.
with my question, some day it can be sovled in the end. >_<
(virtual_env_django_1.7)cundi#cundideAir ~/P/Forum> python manage.py runserver
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/cundi/virtual_env_django_1.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/Users/cundi/virtual_env_django_1.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute
django.setup()
File "/Users/cundi/virtual_env_django_1.7/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/cundi/virtual_env_django_1.7/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/Users/cundi/virtual_env_django_1.7/lib/python2.7/site-packages/django/apps/config.py", line 197, in import_models
self.models_module = import_module(models_module_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/cundi/PycharmProjects/Forum/accounts/models.py", line 6, in <module>
from my_forum.models import Topic, Post
File "/Users/cundi/PycharmProjects/Forum/my_forum/models.py", line 9, in <module>
from utils.bbs_utils import get_delta_time
File "/Users/cundi/PycharmProjects/Forum/utils/bbs_utils.py", line 6, in <module>
from utils import conf
File "/Users/cundi/PycharmProjects/Forum/utils/conf.py", line 4, in <module>
from accounts.models import ForumProfile
ImportError: cannot import name ForumProfile
Using google searched similar Error.But has not solve it.
This is my accounts.models.py files.
may be there is a problem.
class BaseSiteUser(models.Model):
# you can get user info like this: user.base_site_user_set.all()[0]
user = models.OneToOneField(User)
class Profile(BaseSiteUser):
nickname = models.CharField(max_length=12, blank=True, null=True)
user_avatar = models.BooleanField(default=True)
avatar_img = models.ImageField(blank=True, null=True, upload_to='avatar', default='avatar/d_avatar.png')
description = models.TextField(null=True, blank=True)
address = models.CharField(max_length=50, null=True, blank=True)
phone = models.CharField(max_length=11, null=True, blank=True)
born_date = models.DateField(
verbose_name=u'出生日期', null=True, blank=True, default=None)
date_created = models.DateField(null=True, blank=True, verbose_name=u'账户创建日期', auto_now_add=True)
class ForumProfile(Profile):
favorite = models.ManyToManyField(Topic, verbose_name='fav_user', related_name='fav', blank=True)
vote = models.ManyToManyField(Topic, verbose_name='vote_user', related_name='vote', blank=True)
coins = models.IntegerField(default=0, blank=True, null=True)
location = models.CharField(max_length=20, blank=True, null=True)
last_activity = models.DateTimeField(auto_now_add=True)
last_posttime = models.DateTimeField(auto_now_add=True)
signature = models.CharField(max_length=128, default='This guy is lazy that nothing to leave')
website = models.URLField(blank=True, null=True)
This is model.py file's some snippet. Hope it will help.
Does has something wrong with settings.py ?
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = '1-ygln+^^7=5=c)u3#2ozm#jiu)6=65m((rg09pwl069242#vc'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'accounts',
'my_forum',
'utils',
'blog',
'django.contrib.humanize',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'Forum.urls'
WSGI_APPLICATION = 'Forum.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static', 'static_root')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static', 'static_files'),)
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'templates/public'),
)
MAX_UPLOAD_SIZE = "524288"
EMAIL_USE_TLS = True
EMAIL_HOST = ''
EMAIL_PORT = 465
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
SERVER_EMAIL = EMAIL_HOST_USER
LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'),)