Problem on adding Django app to installed apps and can't migrate - python

I'm trying to use visual studio for my Django project. My visual studio version is 2017, my Python version is 3.6 and my Django version at the beginning is 1.1.18.
Then I upgrade it to 2.1.5. I make an app then add it to installed apps. But when I migrate the project get this error:
Traceback (most recent call last):
File "E:\Django_Try\Test4\Test4\manage.py", line 17, in <module>
execute_from_command_line(sys.argv)
File "E:\Django_Try\Test4\Test4\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "E:\Django_Try\Test4\Test4\env\lib\site-packages\django\core\management\__init__.py", line 357, in execute
django.setup()
File "E:\Django_Try\Test4\Test4\env\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "E:\Django_Try\Test4\Test4\env\lib\site-packages\django\apps\registry.py", line 89, in populate
app_config = AppConfig.create(entry)
File "E:\Django_Try\Test4\Test4\env\lib\site-packages\django\apps\config.py", line 90, in create
module = import_module(entry)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\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 'saeed'
The interactive Python process has exited.
The interactive Python process has exited.
>>>
it seems can' identify my app.
my setting:
"""
Django settings for Test4 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 = '79c97724-a0e9-44f0-bffd-e255d60e5460'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
# Add your apps here to enable them
'saeed',
'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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Test4.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 = 'Test4.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']))
it seems can' identify my app.
Please inform me.
Saeed

Edit: It looks like you've renamed your main/base app (the one that contains settings.py) from Test4 to saeed. You do not need to register the base application in a Django project since it is already the entry-point for the program. It looks like the rest of your settings.py file is configured for the base app being called Test4 rather than saeed (you can tell because of ROOT_URLCONF = 'Test4.urls', for example). You can read more about projects and applications in Django here.
Since it's common practice to have your base app share the same name as your project I'd recommend changing the name of the saeed directory (back) to Test4.
If you want to create a new app you can run:
python manage.py startapp saeed
So your project file structure will look something like this:
Test4/ # project directory
saeed/ # your app
migrations/
models.py
apps.py
Test4/ # base app for the site
settings.py
urls.py
manage.py
requirements.txt
Then put your models in saeed instead of Test4. So your project directory Test4/, will contain Test4/, saeed/, and manage.py, among other things. After you create this new app, the following will work:
Original Answer:
Make sure your saeed/apps.py is configured properly, for example:
# saeed/apps.py
from django.apps import AppConfig
class SaeedConfig(AppConfig):
name = "saeed"
verbose_name = "Saeed"
Then you'll want to change that line in INSTALLED_APPS in settings from just "saeed" to
"saeed.apps.SaeedConfig"
See the docs on configuring applications for more on this.

I think, it is the incorrect file location hierarchy.
Should be so, for example.
project
mysite
settings.py
...
saeed
makemigrations
models.py
apps.py
...
manage.py
Read this

Related

Django ImproperlyConfigured

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.

python manage.py collectstatic - Digital Ocean - Django

I tried again to host my django project on digital ocean and I get this error after I send "python manage.py collectstatic". Can you help me interpret this error? I can't understand if it is correlated to my code in django or something that I wrote wrong during the process of hosting the project on the server.
TRACEBACK
(django_env) mattia#droplet:~/piattaforma$ python manage.py collectstatic
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/home/mattia/django_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/mattia/django_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/mattia/django_env/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/mattia/django_env/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute
output = self.handle(*args, **options)
File "/home/mattia/django_env/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle
collected = self.collect()
File "/home/mattia/django_env/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 104, in collect
for path, storage in finder.list(self.ignore_patterns):
File "/home/mattia/django_env/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 130, in list
for path in utils.get_files(storage, ignore_patterns):
File "/home/mattia/django_env/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files
directories, files = storage.listdir(location)
File "/home/mattia/django_env/lib/python3.6/site-packages/django/core/files/storage.py", line 316, in listdir
for entry in os.scandir(path):
FileNotFoundError: [Errno 2] No such file or directory: '/home/mattia/piattaforma/static'
MY DJANGO PROJECT CODE
piattaforma/settings.py
"""
Django settings for piattaforma project.
Generated by 'django-admin startproject' using Django 3.0.5.
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 = '_j*f+(ceue_ff4hrgfk0l&r+)wrp#b8k2o4*snuenmuo$7yxib'
# 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',
'crispy_forms',
'accounts',
'core',
'quiz',
'jobs',
'emoji_picker',
'ckeditor',
]
REGISTRATION_DEFAULT_GROUP_NAME="Students"
CKEDITOR_UPLOAD_PATH = "uploads/"
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 = 'piattaforma.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [ os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'accounts/templates'),
os.path.join(BASE_DIR, 'core/templates'),
os.path.join(BASE_DIR, 'quiz/templates'),
os.path.join(BASE_DIR, 'jobs/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 = 'piattaforma.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
# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# EMAIL_USE_TLS = True
# EMAIL_HOST = 'smtp.gmail.com'
# EMAIL_PORT = 587
# EMAIL_HOST_USER = 'MIO ACCOUNT'
# EMAIL_HOST_PASSWORD = 'MIA PASSWORD'
# DEFAULT_FROM_EMAIL = 'IL MIO ACCOUNT GMAIL'
# DEFAULT_TO_EMAIL = 'TO EMAIL'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_URL = '/static/'
LOGIN_REDIRECT_URL= '/'
piattaforma/manage.py
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'piattaforma.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
You need to setup your STATIC_ROOT variable, that's the absolute path to the directory where collectstatic will collect static files for deployment, according to Django documention.
As you can see here, the STATICFILES_DIRS variable is to set additional directories (instead of only the app ones) that Django will be collect static files and put inside the STATIC_ROOT directory when you run the collectstatic process.
You're getting this error because you're trying to run a collectstatic and it's not finding the directory defines on your STATICFILES_DIRS variable:
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
You can create this directory and put some additional static files that you want to collect in there but you also should set you STATIC_ROOT variable which will be the directory your server is going to use to server the static files on your application.

UnicodeDecodeError: 'utf8' codec can't decode byte 0xc7 in position 27: invalid continuation byte django

I'm trying to upload my django project to Google Cloud Platform.
When I run
python manage.py runserver
an error occurs.
Until a while ago, it worked well.
After fixing codes of just one file 'setting.py' the error occurred.
Here's a screenshot image below.
C:\Users\sgc109\PycharmProjects\pyproj\djenv\Scripts\python.exe C:/Users/sgc109/PycharmProjects/pyproj/my_project/manage.py runserver
Traceback (most recent call last):
File "C:/Users/sgc109/PycharmProjects/pyproj/my_project/manage.py", line 24, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line
utility.execute()
File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\__init__.py", line 355, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\commands\runserver.py", line 62, in execute
super(Command, self).execute(*args, **options)
File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\base.py", line 330, in execute
output = self.handle(*args, **options)
File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\commands\runserver.py", line 101, in handle
self.run(**options)
File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in run
autoreload.main(self.inner_run, None, options)
File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\utils\autoreload.py", line 341, in main
reloader(wrapped_main_func, args, kwargs)
File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\utils\autoreload.py", line 312, in python_reloader
exit_code = restart_with_reloader()
File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\utils\autoreload.py", line 294, in restart_with_reloader
str_value = force_bytes(new_environ[key], encoding=encoding)
File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\utils\encoding.py", line 124, in force_bytes
return s.decode('utf-8', errors).encode(encoding, errors)
File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xc7 in position 27: invalid continuation byte
Process finished with exit code 1
I did my best to find the solution on Google and Stackoverflow, and
I tried hard for finding something wrong in my code, but I couldn't find anything.
Here's my directory structure, my main codes, and Project interpreter settings below. (Because I never changed other
codes in my project and the amount of codes are too many, I won't upload all the
codes in my django project.)
views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return HttpResponse("Hello, world!")
urls.py
from django.conf.urls import url
from django.contrib import admin
from my_app import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.home)
]
settings.py
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/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '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',
'my_app',
]
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 = 'my_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 = 'my_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '/cloudsql/DB Project',
'NAME': 'db-project-185409:asia-northeast1:sgc109',
'USER': 'user',
'PASSWORD': 'password',
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/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.11/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.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = 'static'
manage.py
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
The one thing I think I had a mistake is that
I did 'pip install' for installing Django and MySQL-python
not in virtual environment and did in virtual environment again.
But I'm not sure if it is affecting the error.
Thank you guys for reading my question.
Added
I debugged my code and I found that some directory name which has Korean word is having been passed to some function, but I have no idea why in the world the name of the directory is passed. I'm thinking that the directory which is passed has no relationship with the directory of my django project. Here are screenshots below.
Added2
I found that the directory is one of directories which is included in
environment variables. So I deleted that directory from environment variables
and rebooted my PC, then It worked!!
Was that C7 supposed to be Ç? If so, you have latin1 bytes being treated as utf8. It does not work.
On the other hand, if you specify that you have latin1 bytes, mysql is happy to convert to utf8.
See "Best practice" in Trouble with UTF-8 characters; what I see is not what I stored
and here are some random notes on python: http://mysql.rjweb.org/doc.php/charcoll#python
that go beyond the coding: clause. And search that article for "Django" for how to set the OPTIONS clause.

Django collectstatic error: No such file or directory: '/app/appName/static'

I've been getting this collectstatic error when I run the following in command line:
C:\Users\Steven\site1>heroku run python manage.py collectstatic
Running python manage.py collectstatic on my-compository... up, run.9943 (Free)
You have requested to collect static files at the destination
location as specified in your settings:
/app/mynotes/staticfiles
This will overwrite existing files!
Are you sure you want to do this?
Type 'yes' to continue, or 'no' to cancel: yes
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute
output = self.handle(*args, **options)
File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 193, in handle
collected = self.collect()
File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 115, in collect
for path, storage in finder.list(self.ignore_patterns):
File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/finders.py", line 112, in list
for path in utils.get_files(storage, ignore_patterns):
File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/utils.py", line 28, in get_files
directories, files = storage.listdir(location)
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/files/storage.py", line 399, in listdir
for entry in os.listdir(path):
OSError: [Errno 2] No such file or directory: '/app/mynotes/static'
I haven't been able to figure out what was wrong after much searching.
Here's a slight preview of my directory structure:
-site1
- mynotes
- settings.py
- staticfiles (empty)
- wsgi.py
- urls.py
- mynotess
- static
- mynotess
- capture1.jpg
- carousel.css
- capture2.jpg
- templates
- views.py
- other files related to the app
- users
- files related to this app, no static files here
- manage.py
- .gitignore
- requirements.txt
- Procfile
settings.py
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__)))
DEBUG = False
ALLOWED_HOSTS = ['localhost']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap3',
'mynotess',
'users',
]
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 = 'mynotes.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'mynotes/templates')], #originally empty
'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 = 'mynotes.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/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.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/'
MEDIA_URL = '/media/'
LOGIN_URL = 'users/login'
BOOTSTRAP3 = {'include_jquery': True}
if os.getcwd() == '/app':
import dj_database_url
DATABASES = {
'default': dj_database_url.config(default='postgres://localhost')
}
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
ALLOWED_HOSTS = ['*']
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.normpath(os.path.join(BASE_DIR, 'static'))
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
I don't understand why it's giving this error. It doesn't work with just python manage.py collectstatic either, which gives me an error as follows: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. I've specified the path to the static root mynotes/static and it has been set up to collect all the static files there. I don't understand why it's telling me that no such directory exists. Another thing that confuses me too is the line:
/app/mynotes/staticfiles/
I don't have a directory called staticfiles so I'm not sure how this got here. I typed static in my STATIC_ROOT so I'm not sure why it comes out as staticfiles. Is this something to worry about or is this some default thing? Could it be because I changed the code from the last time I deployed it (which was when DEBUG=True) but it hasn't updated? I tried making an empty directory called staticfiles, but it still gives me the same error.
I'm kind of new to Django and any kind of help is greatly appreciated! P.S. I have thoroughly read the docs but I did not get anything useful out of it.
EDIT
I got heroku run python manage.py collectstatic to work. I figured out why staticfiles was there (just had to re-deploy it). But, my JPG/PNG images and CSS are still not appearing in my website after deployment. This is specifically only when DEBUG = False (it works when True). Plus, python manage.py collectstatic still gives the same error, though I'm not sure if it matters?
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.views.static import serve
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^users/', include('users.urls', namespace='users')),
url(r'', include('mynotess.urls', namespace= "mynotess")), #telling it to look into the urls.py in mynotess for more URLS!
]
if not settings.DEBUG:
urlpatterns += [
url(r'^static/(?P<path>.*)$', serve, {
'document_root': settings.STATIC_ROOT,
}),
]

Django ImportError: No module named middleware

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

Categories

Resources