I'm fairly new to programming and I was learning Python by following the textbook No Starch Python. There is a chapter on Django and I followed the steps of the textbook. However, when I run the program:
from django.db import models
class Topic(models.Model):
"""A topic the user is learning about"""
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
"""Return a string representation of the model."""
return self.text
I will get this error message:
Traceback (most recent call last):
File "/Users/admin/learning_log2/learning_logs/models.py", line 4, in <module>
class Topic(models.Model):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/models/base.py", line 127, in __new__
app_config = apps.get_containing_app_config(module)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/apps/registry.py", line 260, in get_containing_app_config
self.check_apps_ready()
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/apps/registry.py", line 137, in check_apps_ready
settings.INSTALLED_APPS
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/conf/__init__.py", line 92, in __getattr__
self._setup(name)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/conf/__init__.py", line 72, in _setup
raise ImproperlyConfigured(
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.
Here's the settings module:
"""
Django settings for learning_log project.
Generated by 'django-admin startproject' using Django 4.1.5.
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 = 'django-insecure-y8l9_wqzuq6#q#_0=f*$4-k_^o_enm3mmq+oe!*f*i-ktah(9w'
# 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',
]
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 = 'learning_log.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 = 'learning_log.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/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
Can anyone tell me why it is the case and what can I do? Thank you very much.
P.S. I know there is already a post on this but I tried what was written without any results.
Also, I'm on macOS High Sierra version 10.13.6 if this information is relevant.
I tried whatever I could find on the internet but nothing seems to work. I don't even have a fundamental understanding of the problem.
You need to specify the django app name in the settings.py file before start using it.
You were created a Django Application before creating this model 'Topic' with a command
python manage.py startapp core
you need to provide the appname (in the above case it is 'core') under settings.py file in the array like bellow
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'core' #new app name
]
I don't even have a fundamental understanding of the problem
Since you're defining a model, Django assumes that you might want to store instances of that model in a database.
To do that, Django needs to know the connection details for your chosen database, and those details are stored in the settings.py module.
You didn't tell Django where to find that module.
Related
This might probably be a duplicated question, but I can't find a post to answer my questions yet. Any post that is similar to this may help is appreciated.
I tried to host my Django app using heroku.com
git add .
git commit -m "(commit_name)"
git push heroku master
When I tried to test the website (/questions/1), the website shows an Error 500 (Internal Error).
First it shows a ProgrammingError: relation does not exist.
After that I did $ heroku run python manage.py migrate try to solve the problem. The original error disappeared, but instead this happened:
2020-08-29T11:05:42.668070+00:00 app[web.1]: Internal Server Error: /questions/1
2020-08-29T11:05:42.668070+00:00 app[web.1]:
2020-08-29T11:05:42.668070+00:00 app[web.1]: DoesNotExist at /questions/1
2020-08-29T11:05:42.668071+00:00 app[web.1]: Question matching query does not exist.
Settings.py:
import django_heroku
from pathlib import Path
import os
#--------------------(ommited)--------------------#
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
]
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 = 'myweb.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 = 'myweb.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.1/topics/i18n/
LANGUAGE_CODE = 'zh-Hant'
TIME_ZONE = 'Asia/Taipei'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# Activate Django-Heroku.
django_heroku.settings(locals())
Models.py:
from django.db import models
from django.utils import timezone
import json
# Create your models here.
class Code(models.Model):
code = models.TextField()
number = models.IntegerField()
class Question(models.Model):
title = models.TextField()
text = models.TextField()
judges = models.TextField()
number = models.IntegerField()
class Meta:
ordering = ['number']
def set_judges(self, x):
self.judges = json.dumps(x)
def get_judges(self):
return json.loads(self.judges)
wsgi.py:
import os
from dj_static import Cling
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myweb.settings')
application = Cling(get_wsgi_application())
Any suggestions or things I should try? Thank you.
[EDIT]: It seems that the database is empty now so it cause the error. But when I run the same file in my computer as I git push to heroku, the database isn't empty and it works fine.
According to your settings file, you are using sqlite as the database, and you can't use it in Heroku.
Heroku uses an an ephemeral filesystem.
You can write to it, and you can read from it, but the contents will
be cleared periodically. If you were to use SQLite on Heroku, you
would lose your entire database at least once every 24 hours.
That's why it works locally but not on Heroku, you need to use another database engine like postgresql for example.
Learn more about it at: https://help.heroku.com/K1PPS2WM/why-are-my-file-uploads-missing-deleted
I am currently making a project in Django that has two models: Cards and Articles. Both cards and articles have a manager that should allow me to quickly instantiate instances of the class. For cards I have the following:
class CardsManager(models.Manager):
def create_card(self, card_name, geography, player, typestatus, _weighted_strength = 0):
card = self.update_or_create(card_name=card_name, geography=geography, player=player, typestatus=typestatus)
return card
This manager works smoothly and I have no issue uploading cards. However, my article manager is a different story. This is my article manager.
class ArticleManager(models.Manager):
def create_article(self, title, body, cardvar, source, datetime, readthrough, author):
article_item = self.update_or_create(title=title, body=body, card=cardvar, source=source, entry_date_time=datetime, read_through=readthrough, cardvar__card_name=cardvar, author=author)
return article_item
When I try to upload an article however, say in the following fashion:
article_entry = Article.objects.create_article('title', 'empty body', 'test_card_var', 'The_Source', '2019-12-30 02:03:04', 0, 'author')
I get the following error in my Powrshell when I simply attempt 'python manage.py runserver': LookupError: No Installed app with label 'admin'.
When I attempt to run 'python manage.py makemigrations' I get another long error message whose last line is 'django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.'
I think the issue may have to do with something related to either 1) entry_date_time being a datetime object and passing a string (though I honestly am not sure how I'd pass a datetime object, what do they even look like) or b) the fact that cardvar is a ForeignKey pointing at the Cards model, which may not be allowed in an upload?
I really had no issues with uploading Cards but Articles has given serious issues. If anyone could help me resolve this issue it would be greatly appreciated, I'm still relatively new with Django and coding in general.
EDIT:
My Settings.py looks as follows:
"""
Django settings for newspaper_project project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
#import django_heroku
#import psycopg2
#import dj_database_url
#import dotenv
#import psycopg2
#import dj_database_url, psycopg2
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#DATABASE_URL = os.environ['DATABASE_URL']
#conn = psycopg2.connect(DATABASE_URL, sslmode='require')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ***********************
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#3rd party
'crispy_forms', #new
#Local
'users.apps.UsersConfig',
'pages.apps.PagesConfig',
'articles.apps.ArticlesConfig', #new
]
TIME_ZONE = 'America/New_York' #new
USE_TZ = True #TESTING THIS OUT
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 = 'newspaper_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], #new
'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 = 'newspaper_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
AUTH_USER_MODEL = 'users.CustomUser' #new
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' #new
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = '**************************************'
EMAIL_PORT = 587
EMAIL_USE_TILS = True
I keep getting this error when i try to import my models.py file into views.py or any of the other python script in my App directory,
I have the SECRET_KEY in settings.py and also add app in the list of INSTALLED_APPS,
wsgi.py contains
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings') # I replaced my project name
manage.py also contains
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings')
I have checked through other people's installations in StackOverflow posts. My code works but importing models just break it
I use this command to import my class
from app_name.models import subscribers
and subscribers is defined thus
class subscribers(models.Model):
name = models.CharField('Name', max_length=120)
email = models.CharField('Email', max_length=120)
access_token = models.TextField()
expires_in = models.DateTimeField('token expiry date')
I have already executed makemigrations and migrate commands but being a newbie I don't know where else to look. Please save a soul it's been 3 days
thanks.
below is my settings.py
"""
Django settings for ps project.
Generated by 'django-admin startproject' using Django 2.2.6.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
from oauth_outlook.views import gettoken
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY='l!u#h#an5lj%b))=fzhv6r-3ay1&29=ls0*o1_^dxi(01x$et#'
#SECRET_KEY = os.environ.get("SECRET_KEY", "l!u#h#an5lj%b))=fzhv6r-3ay1&29=ls0*o1_^dxi(01x$et#")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'oauth_outlook',
'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',
'lockdown.middleware.LockdownMiddleware',
]
ROOT_URLCONF = 'ps.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 = 'ps.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
LOCKDOWN_PASSWORDS = ('letmein', 'beta')
LOCKDOWN_VIEW_EXCEPTIONS = [
gettoken,
]
It looks like the following import is causing the problem:
from oauth_outlook.views import gettoken
Importing views or models in the settings can cause circular imports and lead to the SECRET_KEY error message even when it is set. I don’t like the way django-lockout is encouraging you to import views for the LOCKDOWN_VIEW_EXCEPTIONS setting.
I suggest you set LOCKDOWN_URL_EXCEPTIONS instead, then the import isn’t required.
LOCKDOWN_URL_EXCEPTIONS = (
r'^gettoken$', # replace with gettoken view
)
This post is a follow-up of this previous question:
Django request.POST empty
I had a project up and running with Python 3.5.4 and Django 1.11.13, on Visual Studio 2015. I later updated to Django 2.1.2 because I wanted to import the "path" module, so that I can use this:
urlpatterns = [
path ( '', c_views.Indice, name = 'indice' ),
path ( '<int:CompiladoID>', c_views.Detalle, name = 'detalle'),
path ( 'elementos/<int:CompiladoID>', c_views.Elementos, name = 'elementos'),
path ( 'datoselementos/<int:ElementoID>', c_views.DatosElemento, name = 'datoselemento'),
...instead of this:
urlpatterns = [
url ( r'^$', c_views.Indice, name = 'indice'),
url ( r'^(?P<CompiladoID>\d+)/$', c_views.Detalle, name = 'detalle' ),
url ( r'^(?P<CompiladoID>\d+)/elementos$', c_views.Elementos, name = 'elementos' ),
url ( r'^(?P<CompiladoID>\d+)/generar$', c_views.Generar, name = 'generar' ),
which I find easier to declare and read. After this change I started to experience problems with request.POST. I got a "request" response, but POST was empty, as shown here:
Actually, I was not initially aware of this. It's taken me 3 days, and a compare with a backup copy that I've recovered, to realize that Django version was different. That said, I'm puzzled about the fact that a newer version of Django should not be able to do something that older versions did, unless something has changed that I don't know of. I've only been working with Python/Django for a couple of months, can anyone tell me if there is a reason to this? Can I not use path instead of url for my urlpatterns using Django 2.1.2?
Thank you in advance for your help.
EDIT (november 14th)
This is my settings.py (I basically added 'app' to INSTALLED_APPS):
"""
Django settings for MemoProject project.
Generated by 'django-admin startproject' using Django 1.9.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
import posixpath
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '---'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'app',
# Add your apps here to enable them
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'MemoProject.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 = 'MemoProject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['static']))
MIDDLEWARE_CLASSES was deprecated in Django 1.10 and removed in Django 2.0. You should be using MIDDLEWARE instead.
You should remove SessionAuthenticationMiddleware because it hasn't been required since Django 1.10.
Django 1.11 gives a deprecation warning that you should switch from MIDDLEWARE, but you must have missed this. Before upgrading Django, it's good practice to read the release notes, and fix any deprecation warnings. See the upgrade guide for more info.
I am using Django version 1.8 and python 2.7. I am getting the following error after running my project.
Traceback (most recent call last):
File "C:\Python27\lib\wsgiref\handlers.py", line 85, in run
self.result = application(self.environ, self.start_response)
File "C:\Python27\lib\site-packages\django\contrib\staticfiles\handlers.py", line 63, in __call__
return self.application(environ, start_response)
File "C:\Python27\lib\site-packages\django\core\handlers\wsgi.py", line 170, in __call__
self.load_middleware()
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 50, in load_middleware
mw_class = import_string(middleware_path)
File "C:\Python27\lib\site-packages\django\utils\module_loading.py", line 26, in import_string
module = import_module(module_path)
File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named middleware
[26/Aug/2015 20:34:29] "GET /favicon.ico HTTP/1.1" 500 59
This is my settings.py file
"""
Django settings for collageapp project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
APP_PATH = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '******************************************************'
# 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',
'manageApp',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.google',
'django.contrib.admindocs',
'rest_framework',
)
SITE_ID = 1
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'corsheaders.middleware.CorsMiddleware',
'oauth2_provider.middleware.OAuth2TokenMiddleware',
)
ROOT_URLCONF = 'collageapp.urls'
CORS_ORIGIN_ALLOW_ALL = True
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',
'allauth.account.context_processors.account',
'allauth.socialaccount.context_processors.socialaccount'
],
},
},
]
WSGI_APPLICATION = 'collageapp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'college_app',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost', # Or an IP Address that your DB is hosted on
'PORT': '3306',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
I have tried surfing the error but in vain. My same code is working fine in other machine.
Open up a python shell by running python manage.py shell in your project directory.
Run the following commands one at a time in the python shell:
>>> from corsheaders.middleware import CorsMiddleware
>>> from oauth2_provider.middleware import OAuth2TokenMiddleware
>>> from django.contrib.auth.middleware import SessionAuthenticationMiddleware
One of the lines should give you an error like the following:
Traceback (most recent call last):
File "<console>", line 1, in <module>
ImportError: No module named middleware
The line that gives you that error is the missing module that is giving you the problem.
To find the path where the modules are searched, do
>>> import sys; sys.path
Alternatively, if you don't know how to use the python shell, you could just remove the following lines in your settings.MIDDLEWARE_CLASSES one at a time until you don't get that error anymore:
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'corsheaders.middleware.CorsMiddleware',
'oauth2_provider.middleware.OAuth2TokenMiddleware',
Just reinstall the package that gave you the error.
django.contrib.auth.middleware -> django
corsheaders.middleware -> corsheaders
oauth2_provider.middleware -> oauth2_provider
Make sure that you have all of the supporting packages installed where they can be found. I've run into problems where there are multiple Python interpreters installed, and was inadvertently running Django with one interpreter while installing packages with another. The other thing I would verify is that you have the same versions of the packages on both machines. Pay close attention to corsheaders.middleware.CorsMiddleware and oauth2_provider.middleware.OAuth2TokenMiddleware since they are not part of Django.
For my situation i did the following:
Inspect the settings.py file
Check on the middleware section for any part that could have been deleted ,accidentally and rectify.
For my case the following had been deleted:
django.middleware.security.SecurityMiddleware