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.
Related
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
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)
The following pages are the code of projects:
If i am using token = jwt.encode(payload,'secret', algorithm='HS256').decode('utf-8') statement
then
'str' object has no attribute 'decode'
error is occuring. Also, when I am removing and using it without .decode('utf-8') and proceeding with the further code. it is working fine. But when I am applying payload = jwt.decode(token, 'secret', algorithm=['HS256'])
then
It is required that you pass in a value for the "algorithms" argument when calling decode()"
This above-mentioned error is occurring. Please Help me to rectify this error. This is the mentioned error that saying algorithms argument when calling decode() error should be rectified.
View Page:
from django.http import request, response
from django.shortcuts import render
from rest_framework import serializers
from rest_framework.views import APIView
from myusers.serializers import UserSerializer
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.response import Response
from .models import User
import jwt, datetime
# Create your views here.
class RegisterView(APIView):
def post(self,request):
serializer = UserSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
class LoginView(APIView):
def post(self,request):
email=request.data['email']
password = request.data['password']
user = User.objects.filter(email=email).first()
if user is None:
raise AuthenticationFailed('User Not Found!!!')
if not user.check_password(password):
raise AuthenticationFailed('Incorrect Password!!!')
payload={
'id':user.id,
'exp':datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
'iat':datetime.datetime.utcnow()
}
token = jwt.encode(payload,'secret', algorithm='HS256').decode('utf-8')
response = Response()
response.data={
"jwt":token
}
response.set_cookie(key='jwt', value=token, httponly=True)
return response
class Userview(APIView):
def get(self,request):
token = request.COOKIES.get('jwt')
if not token:
raise AuthenticationFailed('User Authentication Failed!!!')
try:
payload = jwt.decode(token, 'secret', algorithm=['HS256'])
except jwt.ExpiredSignatureError:
raise AuthenticationFailed('Unauthenticated!')
user = User.objects.filter(id = payload['id']).first()
serializer = UserSerializer(user)
return Response(serializer.data)
class LogoutView(APIView):
def post(self, request):
response = Response()
response.delete_cookie('jwt')
response.data = {
'message': 'success'
}
return response
Serializer Page:
from django.db.models import fields
from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'name','email','password']
extra_kwargs={
'password' : {'write_only':True}
}
def create(self, validated_data):
password = validated_data.pop('password',None)
instance = self.Meta.model(**validated_data)
if password is not None:
instance.set_password(password)
instance.save()
return instance
Model Page:
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
name = models.CharField(max_length=255)
email = models.CharField(max_length=250, unique=True)
password = models.CharField(max_length=255)
username = None
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
Urls page:
from django.urls import path
from .views import RegisterView, LoginView, Userview
urlpatterns = [
path('register',RegisterView.as_view()),
path('login',LoginView.as_view()),
path('user',Userview.as_view()),
path('logout',Userview.as_view()),
]
Setting Page:
"""
Django settings for login project.
Generated by 'django-admin startproject' using Django 4.0.1.
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
# 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 = 'django-insecure-k02ug7k7bm-q0cgy4uini(mol=__ye-cm)$c1q+utmhg86ds$7'
# 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',
'myusers',
'rest_framework',
'corsheaders'
]
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 = 'login.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 = 'login.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
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
AUTH_USER_MODEL = 'myusers.User'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
You're missing an 's', the parameter is called "algorithms" in the decode function:
payload = jwt.decode(token, 'secret', algorithms=['HS256'])
and you're also passing an array of possible values.
When you call encode, the parameter is "algorithm" and only takes a single value.
The reason is that during encoding (i.e signing), you have to use explicitly one algorithm, because a token can only be signed using one algorithm. But during decoding (verifying), you tell the function which algorithms you accept.
Another solution is to downgrade the PyJWT version to 1.7.1, so you wouldn't need to pass the "algorithms" argument.
Like this:
jwt.decode(encoded, verify=False)
I had to pass
verify=False, options={'verify_signature': False} in order to get it working.
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')
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')