Getting error when trying to run to server with Channels - django

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)

Related

Error when upload files to Azure Blob storage through Django App

I need to build a file manager to upload images from a Django app to Azure blob storage. However, when I try to upload a file to Azure's blob storage, I get the following error:
Traceback (most recent call last):
File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/marilynmarquez/Desktop/webster/python/file_manager/website/files/views.py", line 27, in upload_file
new_file=upload_file_to_blob(file)
File "/Users/marilynmarquez/Desktop/webster/python/file_manager/website/files/azure_controller.py", line 57, in upload_file_to_blob
blob_client =create_blob_client(file_name = file_name) #problem
File "/Users/marilynmarquez/Desktop/webster/python/file_manager/website/files/azure_controller.py", line 20, in create_blob_client
storage_credentials = secret_client.get_secret(name=settings.AZURE_STORAGE_KEY_NAME) #problem
File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/core/tracing/decorator.py", line 78, in wrapper_use_tracer
return func(*args, **kwargs)
File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/keyvault/secrets/_client.py", line 72, in get_secret
bundle = self._client.get_secret(
File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/keyvault/secrets/_generated/_operations_mixin.py", line 1574, in get_secret
return mixin_instance.get_secret(vault_base_url, secret_name, secret_version, **kwargs)
File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/core/tracing/decorator.py", line 78, in wrapper_use_tracer
return func(*args, **kwargs)
File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/keyvault/secrets/_generated/v7_3/operations/_key_vault_client_operations.py", line 694, in get_secret
pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access
File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/core/pipeline/_base.py", line 211, in run
return first_node.send(pipeline_request) # type: ignore
File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/core/pipeline/_base.py", line 71, in send
response = self.next.send(request)
File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/core/pipeline/_base.py", line 71, in send
response = self.next.send(request)
File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/core/pipeline/_base.py", line 71, in send
response = self.next.send(request)
[Previous line repeated 2 more times]
File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/core/pipeline/policies/_redirect.py", line 160, in send
response = self.next.send(request)
File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/core/pipeline/policies/_retry.py", line 512, in send
raise err
File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/core/pipeline/policies/_retry.py", line 484, in send
response = self.next.send(request)
File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/core/pipeline/policies/_authentication.py", line 116, in send
self.on_request(request)
File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/keyvault/secrets/_shared/challenge_auth_policy.py", line 71, in on_request
_enforce_tls(request)
File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/keyvault/secrets/_shared/challenge_auth_policy.py", line 41, in _enforce_tls
raise ServiceRequestError(
azure.core.exceptions.ServiceRequestError: Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.
[06/Feb/2023 18:44:58] "POST /upload_file/ HTTP/1.1" 500 155467
This is my azure_controller.py:
from io import BytesIO
import uuid
from pathlib import Path
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
from azure.storage.blob import BlobClient
from django.conf import settings
from . import models
ALLOWED_EXTENSIONS = ['.png', '.jpg']
def create_blob_client(file_name):
default_credential = DefaultAzureCredential()
secret_client=SecretClient(
vault_url = settings.AZURE_VAULT_ACCOUNT,
credential = default_credential
)
storage_credentials = secret_client.get_secret(name=settings.AZURE_STORAGE_KEY_NAME)
return BlobClient(
account_url = settings.AZURE_STORAGE_ACCOUNT,
container_name = settings.AZURE_APP_BLOB_NAME,
blob_name = file_name,
credential = storage_credentials.value,
)
def check_file_ext(path):
ext = Path(path).suffix
return ext in ALLOWED_EXTENSIONS
def download_blob(file):
blob_client=create_blob_client(file)
if not blob_client.exists():
return
blob_content = blob_client.download_blob()
return blob_content
def save_file_url_to_db(file_url):
new_file = models.File.objects.create(file_url = file_url)
new_file.save()
return new_file
def upload_file_to_blob(file):
if not check_file_ext(file.name):
return
file_prefix = uuid.uuid4().hex
ext=Path(file.name).suffix
file_name = f"{file_prefix}{ext}"
file_content = file.read()
file_io = BytesIO(file_content)
blob_client =create_blob_client(file_name = file_name)
blob_client.upload_blob(data=file_io)
file_object=save_file_url_to_db(blob_client.url)
return file_object
This is my settings.py:
Django settings for website project.
from pathlib import Path
import environ
BASE_DIR = Path(__file__).resolve().parent.parent
env = environ.Env()
environ.Env.read_env()
AZURE_STORAGE_ACCOUNT=env.str('AZURE_STORAGE_ACCOUNT')
AZURE_VAULT_ACCOUNT=env.str('AZURE_VAULT_ACCOUNT')
AZURE_STORAGE_KEY_NAME=env.str('AZURE_STORAGE_KEY_NAME')
AZURE_APP_BLOB_NAME=env.str('AZURE_APP_BLOB_NAME')
SECRET_KEY = env('MY_SECRET')
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'files',
'django_extensions',
]
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 = 'website.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 = 'website.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
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',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
STATIC_URL = 'static/'
# Default primary key field type
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
Some of the documentation I read advises using a Security Prncipal in Azure, which implies setting up Azure AD, but every time I try to go to Azure AD in my account, I get a message saying I'm not allowed (I'm the owner of the account). I honestly have no idea where to go from here or how to begin to fix this. Can someone help?
Any help will be greatly appreciated

django.db.utils.OperationalError: near "CASCADE": syntax error when making a pull request in Github

I'm trying to deploy a django website with Heroku.
When I run python3 manage.py runserver, everything works normally. But when I push it to github and make a pull request, I have an action that tests my code and I run into that error.
Using existing test database for alias 'default'...
Found 7 test(s).
System check identified no issues (0 silenced).
.......
Alicia
----------------------------------------------------------------------
Tiffany
Barbara
Ran 7 tests in 1.319s
OK
Taylor
Dr.
Wanda
Jacob
Traceback (most recent call last):
File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/db/backends/utils.py", line 83, in _execute
return self.cursor.execute(sql)
File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 414, in execute
return Database.Cursor.execute(self, query)
sqlite3.OperationalError: near "CASCADE": syntax error
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line
utility.execute()
File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/commands/test.py", line 24, in run_from_argv
super().run_from_argv(argv)
File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/base.py", line 373, in run_from_argv
self.execute(*args, **cmd_options)
File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/base.py", line 417, in execute
output = self.handle(*args, **options)
File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/commands/test.py", line 59, in handle
failures = test_runner.run_tests(test_labels)
File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/test/runner.py", line 941, in run_tests
self.teardown_databases(old_config)
File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django_on_heroku/core.py", line 33, in teardown_databases
self._wipe_tables(connection)
File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django_on_heroku/core.py", line 27, in _wipe_tables
cursor.execute(f"DROP TABLE IF EXISTS {table_name} CASCADE")
File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/db/backends/utils.py", line 83, in _execute
return self.cursor.execute(sql)
File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 414, in execute
return Database.Cursor.execute(self, query)
django.db.utils.OperationalError: near "CASCADE": syntax error
Error: Process completed with exit code 1.
This error appeared after I created a Procfile and added the following changes to my seetings.py:
import django_on_heroku
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
django_on_heroku.settings(locals())
See full settings.py below:
"""
Django settings for website project.
Generated by 'django-admin startproject' using Django 4.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib import Path
import os
import sys
import django_on_heroku
from django.contrib.messages import constants as messages
# 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.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TESTING = len(sys.argv)>1 and sys.argv[1] == 'test'
ALLOWED_HOSTS = []
AUTH_USER_MODEL="register.User"
LOGIN_URL ="/login"
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'register',
'main',
'crispy_forms',
]
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 = 'website.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 = 'website.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.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/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Email config
EMAIL_FROM_USER=os.environ.get('EMAIL_FROM_USER')
EMAIL_HOST='smtp.gmail.com'
EMAIL_HOST_USER=os.environ.get('EMAIL_FROM_USER')
EMAIL_HOST_PASSWORD=os.environ.get('EMAIL_HOST_PASSWORD')
EMAIL_USE_TLS=True
EMAIL_PORT=587
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
CRISPY_TEMPLATE_PACK="bootstrap4"
LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = "/"
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
MESSAGE_TAGS = {
messages.DEBUG: 'alert-info',
messages.ERROR: 'alert-danger',
messages.SUCCESS: 'alert-success',
messages.WARNING: 'alert-warning',
messages.INFO: 'alert-info',
}
django_on_heroku.settings(locals())
and Procfile below:
release: python3 manage.py makemigrations
release: python3 manage.py migrate
web: gunicorn website.wsgi
If you have an idea how to solve this, please let me know.
Thanks.
SQLite doesn't support that SQL syntax from the django_on_heroku package, which is why you see the error.
You can see details on DROP TABLE for SQLite here, but to quote that page;
SQLite doesn’t support the CASCADE and RESTRICT keywords, which are included in the SQL standard, and are supported by some other RDBMSs (such as PostgreSQL).
There's a good chance that your server is running mysql or postgres, but your tests use SQLite.
You've mentioned that a github workflow is where the problem occurs, so I'd look to use mysql or postgres in that workflow. You can see examples of this here.

createsuperuser fails on postgresql only

I am able to get my code and database to work just fine locally using sqlite3. But when I try and migrate to a postgresql platform, I get errors when I try to create the superuser, but not migrate or makemigration.
(trader) bubba#tuna:~/www/src/trader $ ./manage.py makemigrations
No changes detected
(trader) bubba#tuna:~/www/src/trader $ ./manage.py migrate
Operations to perform:
Apply all migrations: accounts, admin, auth, contenttypes, sessions
Running migrations:
No migrations to apply.
(trader) bubba#tuna:~/www/src/trader $ ./manage.py createsuperuser
Username (leave blank to use 'bubba'):
Email address: bubba#trader.com
Password:
Password (again):
Traceback (most recent call last):
File "./manage.py", line 21, in <module>
main()
File "./manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute
return super().execute(*args, **options)
File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute
output = self.handle(*args, **options)
File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle
self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/contrib/auth/models.py", line 158, in create_superuser
return self._create_user(username, email, password, **extra_fields)
File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/contrib/auth/models.py", line 141, in _create_user
user.save(using=self._db)
File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 66, in save
super().save(*args, **kwargs)
File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/db/models/base.py", line 746, in save
force_update=force_update, update_fields=update_fields)
File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/db/models/base.py", line 795, in save_base
update_fields=update_fields, raw=raw, using=using,
File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in send
for receiver in self._live_receivers(sender)
File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp>
for receiver in self._live_receivers(sender)
File "/home/bubba/www/src/trader/accounts/signals.py", line 10, in customer_profile
group = Group.objects.get(name='customer')
File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/db/models/query.py", line 417, in get
self.model._meta.object_name
django.contrib.auth.models.DoesNotExist: Group matching query does not exist.
These are my settings
$ cat trader/settings.py
"""
Django settings for trader project.
Generated by 'django-admin startproject' using Django 3.0.6.
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 = 'boo'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1', '192.168.42.14']
ALLOWED_CIDR_NETS = ['192.168.42.0/24']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts.apps.AccountsConfig',
'django_filters',
]
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 = 'trader.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 = 'trader.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'expungee',
'USER':'boo',
'PASSWORD':'boo',
'HOST':'192.168.42.13',
'PORT':'5432',
}
}
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, '/home/bubba/www/src/trader/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/'
MEDIA_URL = '/images/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
STATICFILES_DIRS = [
os.path.join(BASE_DIR, '/static')
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')
I did try
django.db.backends.postgresql
but could not even connect.
exchangedb=# \du
List of roles
Role name | Attributes | Member of
---------------+------------------------------------------------------------+-----------
administrator | Superuser, Create role, Create DB | {}
expungee | Superuser, Create role, Create DB | {}
expungeedb | | {}
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
How do I migrate to postgres?
UPDATED:
$ cat accounts/signals.py
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.contrib.auth.models import Group
from .models import Customer
def customer_profile(sender, instance, created, **kwargs):
if created:
group = Group.objects.get(name='customer')
instance.groups.add(group)
Customer.objects.create(
user=instance,
name=instance.username,
)
print('Profile created!')
post_save.connect(customer_profile, sender=User)
replace this line with a get or create call
group, created = Group.objects.get_or_create(name='customer')
python3 manage.py migrate
python3 manage.py createsuperuser

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.

TangoWithDjango | 5.8 Creating a Population Script | Import Error

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