Django Templates and Apps Not Loading - python

The title says most of it. I'm running Unittests.py in PyCharm on a tutorial and my templates folder is nested directly beneath my app folder (superlists/lists/templates/home.html).
So here's the test I'm running superlists/lists/tests.py:
def test_home_page_returns_correct_html(self):
request = HttpRequest()
response = home_page(request)
expected_html = render_to_string('home.html')
self.assertEqual(response.content.decode(), expected_html)
And here's the code it's being run on (superlists/lists/views.py)
def home_page(request):
return render(request, 'home.html')
And here's the error:
Error
Traceback (most recent call last):
File "C:\Users\Me\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\utils.py", line 86, in __getitem__
return self._engines[alias]
KeyError: 'django'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Me\PycharmProjects\superlists\lists\tests.py", line 19, in test_home_page_returns_correct_html
response = home_page(request)
File "C:\Users\Me\PycharmProjects\superlists\lists\views.py", line 8, in home_page
return render(request, 'home.html')
File "C:\Users\Me\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\shortcuts.py", line 67, in render
template_name, context, request=request, using=using)
File "C:\Users\Me\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\loader.py", line 96, in render_to_string
template = get_template(template_name, using=using)
File "C:\Users\Me\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\loader.py", line 26, in get_template
engines = _engine_list(using)
File "C:\Users\Me\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\loader.py", line 143, in _engine_list
return engines.all() if using is None else [engines[using]]
File "C:\Users\Me\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\utils.py", line 110, in all
return [self[alias] for alias in self]
File "C:\Users\Me\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\utils.py", line 110, in <listcomp>
return [self[alias] for alias in self]
File "C:\Users\Me\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\utils.py", line 101, in __getitem__
engine = engine_cls(params)
File "C:\Users\Me\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\backends\django.py", line 31, in __init__
options['libraries'] = self.get_templatetag_libraries(libraries)
File "C:\Users\Me\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\backends\django.py", line 49, in get_templatetag_libraries
libraries = get_installed_libraries()
File "C:\Users\Me\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\backends\django.py", line 121, in get_installed_libraries
for app_config in apps.get_app_configs())
File "C:\Users\Me\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\apps\registry.py", line 137, in get_app_configs
self.check_apps_ready()
File "C:\Users\Me\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\apps\registry.py", line 124, in check_apps_ready
**raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.**
So, I checked two places in settings.py, INSTALLED_APPS and TEMPLATES.
Here's both sections:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'lists',
]
and
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',
],
},
},
]
Here's a short list of things I've tried:
*Changing the source code of tests.py and views.py to have most combinations of the path to home.html
*Changing the path listed in INSTALLED_APPS and TEMPLATES to have most combinations of varying lengths to the paths of lists and home.html
*Changing 'DIRS': [] to 'DIRS': [os.path.join(BASE_DIR, 'templates')],
Sidenote: I've also had to repeatedly put DJANGO_SETTINGS_MODULE=(project directory name).settings as an environment variable in PyCharm, using the solution to an error, here, because the other solutions didn't work, so, I recognize that my setup may be just a tad buggy.

Your problem isn't related to template, but wrong test configuration in PyCharm.
It seems you are using Python tests -> Unittests configuration for your tests, PyCharm provides a specific configuration for Django tests (it automatically loads the right django settings).
So follow this steps to configure it:
Go to the menu Run -> Edit Configurations...
Click on the green plus icon
Select Django tests
Optionally enter the Django app name in the Target field (lists in your case)
If you have configured your django project and python interpreter in your PyCharm settings it should work.
Hope this helps.

Related

Intellj python test: run individual Django tests

I have Django application inside IntelliJ IDE.
I can run all Django tests by calling the Django Tests runner.
But:
This is a time consuming and not ideal for development, where you would like to rerun one test that fail, and not run all 1000 others that are ok.
IntelliJ has options (UI) to run one test quickly, but this run python tests runner.
I add DJANGO_SETTINGS_MODULE=... inside, but now I get other errors:
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
I was looking to solve this error and I only found :
import django
django.setup()
inside Settings.py
My problem with this is:
I think this breaks normal behaviour of the app. App works normal for different environments.
It doesn't call code after this setup inside settings, so secret_key and others are not installed
This doesn't seam to be really related to tests, but is changing the whole app.
So, I am looking for some settings, how to set the normal python tests, so that they will run as django tests.
EDIT:
Now I change some thinks around and do:
Separate Settings for test
Do all the imports and then django.setup()
Now I get different error:
# The settings_test.py
SECRET_KEY = 'kdbaskdbkjadasd'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mobileapp',
]
DEBUG = True
ALLOWED_HOSTS = '*'
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',
]
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 = '...wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': '...',
'USER': '...',
'PASSWORD': '...',
'HOST': 'localhost',
'PORT': 5432,
}
}
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_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
import django
django.setup()
error:
/Users/zadravecm/Work/.../env/bin/python3.6 /Users/zadravecm/Work/.../tests/tests.py
Traceback (most recent call last):
File "/Users/zadravecm/Work/.../tests/tests.py", line 2, in <module>
from ....Services import subsidiary_service as sub_service
File "/Users/zadravecm/Work/.../Services/subsidiary_service.py", line 3, in <module>
from ....models import *
File "/Users/zadravecm/Work/.../models.py", line 2, in <module>
from django.contrib.auth.models import User
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module>
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in <module>
class AbstractBaseUser(models.Model):
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/db/models/base.py", line 107, in __new__
app_config = apps.get_containing_app_config(module)
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/apps/registry.py", line 252, in get_containing_app_config
self.check_apps_ready()
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/apps/registry.py", line 134, in check_apps_ready
settings.INSTALLED_APPS
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__
self._setup(name)
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/conf/__init__.py", line 63, in _setup
self._wrapped = Settings(settings_module)
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/conf/__init__.py", line 142, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/Users/zadravecm/Work/.../env/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/Users/zadravecm/Work/.../settings_test.py", line 121, in <module>
django.setup()
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/apps/registry.py", line 122, in populate
app_config.ready()
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 24, in ready
self.module.autodiscover()
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/Users/zadravecm/Work/.../env/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/Users/zadravecm/.../env/lib/python3.6/site-packages/django/contrib/auth/admin.py", line 6, in <module>
from django.contrib.auth.forms import (
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/contrib/auth/forms.py", line 10, in <module>
from django.contrib.auth.models import User
ImportError: cannot import name 'User'
EDIT:
The image of the settings of a test runner that is run automatically, if I click run icon on tests.

Django settings module exception

I got the following error:
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\pydevd.py", line 1741, in <module>
main()
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\pydevd.py", line 1735, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\pydevd.py", line 1135, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Apache24/htdocs/consult/accounts/models.py", line 7, in <module>
from django.contrib.auth.models import AbstractUser
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\contrib\auth\models.py", line 2, in <module>
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module>
class AbstractBaseUser(models.Model):
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\db\models\base.py", line 87, in __new__
app_config = apps.get_containing_app_config(module)
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\apps\registry.py", line 249, in get_containing_app_config
self.check_apps_ready()
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\apps\registry.py", line 131, in check_apps_ready
settings.INSTALLED_APPS
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\conf\__init__.py", line 57, in __getattr__
self._setup(name)
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\conf\__init__.py", line 42, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\_pydevd_bundle\pydevd_xml.py", line 179, in _get_type
if isinstance(o, t[0]):
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\utils\functional.py", line 213, in inner
self._setup()
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\conf\__init__.py", line 42, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested settings, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
I am very new to Python programming. Please help me to resolve this and let me know how to set PYTHON ENVIRONMENT VARIABLE.
this is my settings.py
INSTALLED_APPS =
[
'accounts',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_mysql',
]
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 = 'consult.urls'
TEMPLATES =
[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['/templates/accounts/'],
'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 = 'consult.wsgi.application'
DATABASES =
{
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'suitecaredb',
'USER': 'root',
'PASSWORD': 'innovations',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
'charset': 'utf8mb4',
},
'TEST': {
'CHARSET': 'utf8mb4',
'COLLATION': 'utf8mb4_unicode_ci',
}
}
}
AUTH_USER_MODEL = "accounts.User"
To open a python terminal with the Django environment set run
python manage.py shell
Then, for example, a new user can be created with the create_user() helper function:
>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('john', 'lennon#thebeatles.com', 'johnpassword')
# At this point, user is a User object that has already been saved
# to the database. You can continue to change its attributes
# if you want to change other fields.
>>> user.last_name = 'Lennon'
>>> user.save()
The example code below shows how to add a user from a script. Note that you need to replace 'project.settings' on line 2 with your project name.
project.setting points at your project file where installed apps, middleware, templates, etc are specified.
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE','project.settings')
import django
django.setup()
from django.contrib.auth.models import User
super_user = User.objects.create_user(username = 'john',
first_name = 'John',
last_name = 'Doe',
email = 'john.doe#mail.com',
password = 'test',
is_staff = True,
is_superuser=True
)
More information in the documentation docs.djangoproject.com
On setting:
wsgi.py
Check if it is pointing to the right setting path:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "path/to/settings.py")
Try out the following:
As mentioned in the above answer, ensure that the following line is present in wsgi.py
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "/path/to/settings.py")
Ensure that above path is correct or the mentioned settings file in above line is the actual settings file.
Since you are using Pycharm, the above error could because cause of some issue with the Pycharm environment variable. Try python manage.py flush.
If the issue still persists, have a look at the environment configuration in the Pycharm settings and check for any discrepancy.

Restructure default hierarchy of Django project, moving all apps into a folder with custom model

I am trying to move all the apps that I have in my Django application to a folder call apps:
The structure that I have right now is:
miApp
-accounts #App folder
-participation #App folder
-administration #App folder
-miapp
--wsgi.py
--urls.py
--settings
---development.py
---production.py
---__init__.py
-static
And I would like to have something like this
miApp
-apps #New folder for the apps
--accounts #App folder
--reputation #App folder
--participation #App folder
--administration #App folder
--__init__.py
-miApp
--wsgi.py
--urls.py
--settings
---common.py #Common settings for develpment and production
---development.py
---production.py
---__init__.py
-static
...
I tried already to move them all to the same folder,
I did the following change in miApp.urls
path('', views.inicio, name='inicio'),
path('admin/', admin.site.urls),
path('cuentas/', include('apps.accounts.urls')),
path('participation/', include('apps.participation.urls')),
path('administracion/', include('apps.administration.urls')),
And also this, in the settings of common.py
DJANGO_APPS = ['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites'
]
THIRD_PARTIES = [# Django AllAuth
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.google',
'allauth.socialaccount.providers.twitter',
# Django guardian
'guardian',
#Django meta
'meta',
# Django push notifications
'push_notifications',
]
MI_APP_APPS = [# MyVoto Instaled apps
'apps.accounts.apps.AccountsConfig',
'apps.participation.apps.ParticipationConfig',
'apps.administration.apps.AdministrationConfig']
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTIES + MI_APP_APPS
I have the following config classes in apps.py
class AccountsConfig(AppConfig):
name = 'apps.accounts'
class AdministrationConfig(AppConfig):
name = 'apps.administration'
class ParticipationConfig(AppConfig):
name = 'apps.participation'
And I am getting the following error:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x107afa488>
Traceback (most recent call last):
File "/Users/robertofernandez/PycharmProjects/miApp/venv/lib/python3.6/site-packages/django/apps/config.py", line 143, in create
app_module = import_module(app_name)
File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'accounts'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/robertofernandez/PycharmProjects/miApp/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "/Users/robertofernandez/PycharmProjects/miApp/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run
autoreload.raise_last_exception()
File "/Users/robertofernandez/PycharmProjects/miApp/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception
raise _exception[1]
File "/Users/robertofernandez/PycharmProjects/miApp/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute
autoreload.check_errors(django.setup)()
File "/Users/robertofernandez/PycharmProjects/miApp/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "/Users/robertofernandez/PycharmProjects/miApp/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/robertofernandez/PycharmProjects/miApp/venv/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate
app_config = AppConfig.create(entry)
File "/Users/robertofernandez/PycharmProjects/miApp/venv/lib/python3.6/site-packages/django/apps/config.py", line 147, in create
app_name, mod_path, cls_name,
django.core.exceptions.ImproperlyConfigured: Cannot import 'accounts'. Check that 'apps.accounts.apps.AccountsConfig.name' is correct.
I have the following in apps.accounts.apps.py
class AccountsConfig(AppConfig):
name = 'accounts'
I think that's not a good practice to move apps folders this way but did you try to add a __init__.py file in apps?
miApp
-apps #New folder for the apps
--accounts #App folder
--reputation #App folder
--participation #App folder
--administration #App folder
--__init__.py
EDIT
Ithink the problem is the location of your apps.py file. From what you have in INSTALLED_APPS, it tries to get your config classes from an apps.py in every app folder.
Check this answer, the guy describes exactly what you're trying to do.
Really make sure you have the __init__.py file inside your apps folder and inside each app folder.
Move your apps
Change your prefix your apps in INSTALLED_APPS and urls.py by apps.
The problem was that as I am using a custom user model in my common.py I had this:
AUTH_USER_MODEL = 'accounts.User'
With the changes I was doing, I also add the prefix apps to this setting,
don't know why this setttings it works different, but instead of adding the prefix apps I had to leave it like it was before.
I think it maybe cause of the initial migration, that some how as is in the initial migration where the custom model is set up, probably the route is store somewhere and that maybe the thing causing the problem

Django settings not working correctly

I am able to execute
python manage.py migrate - it executes perfectly
But when I run
django-admin shell
it fails giving the following errors
Traceback (most recent call last):
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/core/management/base.py", line 337, in execute
saved_locale = translation.get_language()
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/utils/translation/__init__.py", line 190, in get_language
return _trans.get_language()
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/utils/translation/__init__.py", line 57, in __getattr__
if settings.USE_I18N:
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/conf/__init__.py", line 39, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/cj/.vtenv/officingx/bin/django-admin", line 11, in <module>
sys.exit(execute_from_command_line())
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/core/management/base.py", line 306, in run_from_argv
connections.close_all()
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/db/utils.py", line 229, in close_all
for alias in self:
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/db/utils.py", line 223, in __iter__
return iter(self.databases)
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/db/utils.py", line 156, in databases
self._databases = settings.DATABASES
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/conf/__init__.py", line 39, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
My settings.py
"""
Django settings for officingx project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
import dj_database_url
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['OFFICINGX_SECRET_KEY']
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'amenity.apps.AmenityConfig',
'booking.apps.BookingConfig',
'location.apps.LocationConfig',
'organization.apps.OrganizationConfig',
'photo.apps.PhotoConfig',
'product.apps.ProductConfig',
'property.apps.PropertyConfig',
]
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 = 'officingx.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'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 = 'officingx.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {'default': dj_database_url.config()}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/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.10/howto/static-files/
STATIC_URL = '/static/'
Please help I can't understand why its not able read the settings even when migrate command is working perfectly fine
Taken from the docs:
Generally, when working on a single Django project, it’s easier to use manage.py than django-admin. If you need to switch between multiple Django settings files, use django-admin with DJANGO_SETTINGS_MODULE or the --settings command line option.
You didn't specify a --settings module (as an argument) in the django-admin, that's why Django complains. Do it like this: django-admin shell --settings=myproject.settings.
Also, from the docs:
The settings module should be in Python package syntax, e.g. mysite.settings. If this isn’t provided, django-admin will use the DJANGO_SETTINGS_MODULE environment variable.
You can also do ./manage.py shell

Django error in django-social-auth

I am newbie in Django. I am implementing the facebook authentication in my app. The Error that i am getting in my terminal output is like ;
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 324, in execute
django.setup()
File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/usr/local/lib/python2.7/dist-packages/social_auth/models.py", line 4, in <module>
from django.utils.importlib import import_module
ImportError: No module named importlib
What i am doing wrong? IS my newly installed django-python-social installed correctly?
It seems like django-social-auth have already issues with django 1.8, so I don't wonder if it has problems with django 1.9. I will recommand to use django-allauth since it's the most used/rated package for social network, and it's easy to configure:
pip install django-allauth
settings.py config
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
....
"django.core.context_processors.request",
# allauth specific context processors
"allauth.account.context_processors.account",
"allauth.socialaccount.context_processors.socialaccount",
],
},
},]
AUTHENTICATION_BACKENDS = (
# Default backend
"django.contrib.auth.backends.ModelBackend",
# `allauth` specific authentication methods, such as login by e-mail
"allauth.account.auth_backends.AuthenticationBackend",
)
INSTALLED_APPS += (
# The Django sites framework is required
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
# Login Facebook provider
'allauth.socialaccount.providers.facebook',
)
SITE_ID = 1
in urls.py add:
urlpatterns = patterns('',
...
#Auth URLS
url(r'^accounts/', include('allauth.urls')),
)
Finally apply database migration
run server and go to the admin interface at
http://127.0.0.1:8000/admin/sites/site and create a Site for
the localhost, 127.0.0.1:8000, or your website domain for
production. It should have an id equal to the SITE_ID configured
before in the setting.
Configure your facebook app to get secret key, and then create a Social Application for Facebook at http://127.0.0.1:8000/admin/socialaccount/socialapp
--> you may also find this tutoriel useful
django-social-auth has officially been deprecated in favour of python-social-auth. So you should not be using it. Moreover the import error is most probably due to incompatibility with Django 1.9 as importlib has been deprecated from django.

Categories