Django not able to render context when in shell - python

This is what I am trying to run. When I run the server and run these lines within a view and then return an HttpResponse, then everything goes fine. However when I run python manage.py shell and then try to run through these lines then I get an error:
product = Product.objects.get(pk=4)
template = loader.get_template('weekly-email.html')
user = User.objects.get(pk=1)
body = template.render(Context({
'user': user,
'product': product,
}))
Output:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/croberts/.virtualenvs/testproj/lib/python3.4/site-packages/django/template/backends/django.py", line 74, in render
return self.template.render(context)
File "/Users/croberts/.virtualenvs/testproj/lib/python3.4/site-packages/django/template/base.py", line 209, in render
return self._render(context)
File "/Users/croberts/.virtualenvs/testproj/lib/python3.4/site-packages/django/template/base.py", line 201, in _render
return self.nodelist.render(context)
File "/Users/croberts/.virtualenvs/testproj/lib/python3.4/site-packages/django/template/base.py", line 903, in render
bit = self.render_node(node, context)
File "/Users/croberts/.virtualenvs/testproj/lib/python3.4/site-packages/django/template/base.py", line 917, in render_node
return node.render(context)
File "/Users/croberts/.virtualenvs/testproj/lib/python3.4/site-packages/django/template/base.py", line 963, in render
return render_value_in_context(output, context)
File "/Users/croberts/.virtualenvs/testproj/lib/python3.4/site-packages/django/template/base.py", line 939, in render_value_in_context
value = localize(value, use_l10n=context.use_l10n)
File "/Users/croberts/.virtualenvs/testproj/lib/python3.4/site-packages/django/utils/formats.py", line 181, in localize
return number_format(value, use_l10n=use_l10n)
File "/Users/croberts/.virtualenvs/testproj/lib/python3.4/site-packages/django/utils/formats.py", line 162, in number_format
get_format('DECIMAL_SEPARATOR', lang, use_l10n=use_l10n),
File "/Users/croberts/.virtualenvs/testproj/lib/python3.4/site-packages/django/utils/formats.py", line 110, in get_format
for module in get_format_modules(lang):
File "/Users/croberts/.virtualenvs/testproj/lib/python3.4/site-packages/django/utils/formats.py", line 82, in get_format_modules
modules = _format_modules_cache.setdefault(lang, list(iter_format_modules(lang, settings.FORMAT_MODULE_PATH)))
File "/Users/croberts/.virtualenvs/testproj/lib/python3.4/site-packages/django/utils/formats.py", line 51, in iter_format_modules
if not check_for_language(lang):
File "/Users/croberts/.virtualenvs/testproj/lib/python3.4/site-packages/django/utils/translation/__init__.py", line 181, in check_for_language
return _trans.check_for_language(lang_code)
File "/Users/croberts/.virtualenvs/testproj/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/Users/croberts/.virtualenvs/testproj/lib/python3.4/site-packages/django/utils/translation/trans_real.py", line 409, in check_for_language
if not language_code_re.search(lang_code):
TypeError: expected string or buffer
edit: and here is my settings.py:
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
DEBUG = True
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'SECRET'
ALLOWED_HOSTS = []
AUTH_USER_MODEL = 'crunch.User'
STATICFILES_DIRS = (
'/Users/croberts/testproj/static/',
)
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crunch',
'emailmanager',
)
MIDDLEWARE_CLASSES = (
'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',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'testproj.urls'
WSGI_APPLICATION = 'testproj.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'database'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'MST'
USE_I18N = True
USE_L10N = True
USE_TZ = False
STATIC_URL = '/static/'
MEDIA_ROOT = BASE_DIR+'/media/'
MEDIA_URL = '/media/'
Also, I am using django 1.8.

This is a known issue and will be fixed in 1.8.1.
Meanwhile, you can manually activate a language in your shell to fix it:
from django.utils.translation import activate
activate('en') # or any language code
UPDATE: 1.8.1 has been released, so the best solution is to upgrade to the latest 1.8.x version.

Related

not able to run manage.py runserver

Below is the problem i am facing while running the server.
I'm not able to start manage.py runserver . I'm Using sqlite3 database. I am trying to run quite basic application. system configurations: windows 10, python 2.7.
Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.
C:\Users\rutwi_000>cd C:\Python27\Scripts\mysite
C:\Python27\Scripts\mysite>C:/Python27/python manage.py runserver
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 350, in execute_from_command_line
utility.execute()
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 342, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 195, in fetch_command
klass = load_command_class(app_name, subcommand)
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 39, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 16, in <module>
from django.db.migrations.executor import MigrationExecutor
File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 7, in <module>
from .loader import MigrationLoader
File "C:\Python27\lib\site-packages\django\db\migrations\loader.py", line 10, in <module>
from django.db.migrations.recorder import MigrationRecorder
File "C:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 12, in <module>
class MigrationRecorder(object):
File "C:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 26, in MigrationRecorder
class Migration(models.Model):
File "C:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 27, in Migration
app = models.CharField(max_length=255)
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1072, in __init__
super(CharField, self).__init__(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 166, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 55, in __getattr__
self._setup(name)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 43, in _setup
self._wrapped = Settings(settings_module)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 99, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "C:\Python27\Scripts\mysite\mysite\settings.py", line 15, in <module>
django.setup()
File "C:\Python27\lib\site-packages\django\__init__.py", line 17, in setup
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 55, in __getattr__
self._setup(name)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 43, in _setup
self._wrapped = Settings(settings_module)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 120, in __init__
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
Please help me with this question. Thanks!!!!!!
Below is the settings.py file.
Note: I do have a security key (not shown in the code below)
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.9.
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 django
django.setup()
# 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 = [
'personal',
'blog',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
]
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 = 'mysite.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 = 'mysite.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/'
Your error traceback clearly states that your SECRET_KEY is empty
raise ImproperlyConfigured("The SECRET_KEY setting must not be
empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
Generate a new one, you can use this
"""
Pseudo-random django secret key generator.
- Does print SECRET key to terminal which can be seen as unsafe.
"""
from __future__ import print_function
import string
import random
# Get ascii Characters numbers and punctuation (minus quote characters as they could terminate string).
chars = ''.join([string.ascii_letters, string.digits, string.punctuation]).replace('\'', '').replace('"', '').replace('\\', '')
SECRET_KEY = ''.join([random.SystemRandom().choice(chars) for i in range(50)])
print(SECRET_KEY)
save this in secret_key.py file, and do python secret_key.py, it will generate you a new SECRET KEY, then just copy new SECRET_KEY inside you're settings.py file.

Django 1.10 Translation

I was trying internationalization/localization in django.
I am getting an error while i am trying to make the '.po' files using the command
./manage.py makemessages
relevant parts from settings.py
import os
from django.utils.translation import ugettext_lazy as _
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls.apps.PollsConfig'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'sampleproject.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',
'django.template.context_processors.i18n'
],
},
},
]
WSGI_APPLICATION = 'sampleproject.wsgi.application'
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LANGUAGES = [
('fi-FI', _('Finnish')),
('en', _('English')),
]
LOCALE_PATHS = [
os.path.join(BASE_DIR, 'locale'),
]
relevant parts from urls.py
urlpatterns += i18n_patterns(
url(r'^$', home, name='home'),
url(r'^admin/', include(admin.site.urls)),
url(r'^polls/', include('polls.urls')),
)
here is the traceback.
Traceback (most recent call last):
File "./manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/base.py", line 305, in run_from_argv
self.execute(*args, **cmd_options)
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/base.py", line 356, in execute
output = self.handle(*args, **options)
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/commands/makemessages.py", line 361, in handle
potfiles = self.build_potfiles()
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/commands/makemessages.py", line 393, in build_potfiles
self.process_files(file_list)
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/commands/makemessages.py", line 488, in process_files
self.process_locale_dir(locale_dir, files)
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/commands/makemessages.py", line 507, in process_locale_dir
build_file.preprocess()
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/commands/makemessages.py", line 113, in preprocess
content = templatize(src_data, self.path[2:])
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/utils/translation/__init__.py", line 214, in templatize
return _trans.templatize(src, origin)
File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/utils/translation/trans_real.py", line 670, in templatize
"%s (%sline %d)" % (t.contents, filemsg, t.lineno)
SyntaxError: Translation blocks must not include other block tags: blocktrans count var|length as count (file htmlcov/_project_Myapps_for_sample_lib_python3_4_site-packages_django_templatetags_i18n_py.html, line 1073)
Dev Setup:
Django 1.10
Python 3.4.5
As this is my first question in SO, pardon me if there's any mistake :)
Thanks in advance :)
The error occurred because of the htmlcov folder which was generated while running the coverage script.
Removed that folder and executed the following commands to generate the '.po' files.
./manage.py makemessages -l fi
and the following command to generate the '.mo' files.
./manage.py compilemessages

Django Tincymce, AttributeError: 'NoneType' object has no attribute 'endswith'

I added Tinymce to my django project. But now i cant start django test server. I'm getting following error.
(postjust)erkans-MacBook-Air:postjust erkan$ python manage.py runserver
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/erkan/Dev/Python/virtualenvs/postjust/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/Users/erkan/Dev/Python/virtualenvs/postjust/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute
django.setup()
File "/Users/erkan/Dev/Python/virtualenvs/postjust/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/erkan/Dev/Python/virtualenvs/postjust/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/Users/erkan/Dev/Python/virtualenvs/postjust/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/usr/local/Cellar/python/2.7.8_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/erkan/Dev/Python/virtualenvs/postjust/lib/python2.7/site-packages/tinymce/models.py", line 6, in <module>
from tinymce import widgets as tinymce_widgets
File "/Users/erkan/Dev/Python/virtualenvs/postjust/lib/python2.7/site-packages/tinymce/widgets.py", line 10, in <module>
import tinymce.settings
File "/Users/erkan/Dev/Python/virtualenvs/postjust/lib/python2.7/site-packages/tinymce/settings.py", line 16, in <module>
JS_ROOT = getattr(settings, 'TINYMCE_JS_ROOT',os.path.join(settings.STATIC_ROOT, 'tiny_mce'))
File "/Users/erkan/Dev/Python/virtualenvs/postjust/bin/../lib/python2.7/posixpath.py", line 77, in join
elif path == '' or path.endswith('/'):
AttributeError: 'NoneType' object has no attribute 'endswith'
I have Static_Url in my settings.
my settings.py :
"""
Django settings for postjust project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'jb-#(98(ew4kkociwv+2y(3799r*vug7-$g)e=6wsxigrk30=!'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['localhost','127.0.0.1']
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions',
'blog',
'pages',
'tinymce'
)
MIDDLEWARE_CLASSES = (
'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',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'pages.context_processors.pages'
)
ROOT_URLCONF = 'postjust.urls'
WSGI_APPLICATION = 'postjust.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/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.7/howto/static-files/
STATIC_URL = '/static/'
i try yo set static_url to '' and '/'. What is the solution ?
You need to have a STATIC_ROOT in your settings, not only STATIC_URL. Docs can be found here

TypeError: unhashable type: 'bytearray'

I'm new to django and trying to create a Homepage. But I've already problems with the database setup. When I run
python manage.py migrate
I get this error
(env) paul#Kreker-Server:~/public_html/p_kreker$ python manage.py migrate
Operations to perform:
Apply all migrations: auth, sessions, contenttypes, admin
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying sessions.0001_initial... OK
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 165, in handle
emit_post_migrate_signal(created_models, self.verbosity, self.interactive, connection.alias)
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/core/management/sql.py", line 268, in emit_post_migrate_signal
using=db)
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/dispatch/dispatcher.py", line 198, in send
response = receiver(signal=self, sender=sender, **named)
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/contrib/auth/management/__init__.py", line 64, in create_permissions
if not is_latest_migration_applied('auth'):
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/db/migrations/loader.py", line 292, in is_latest_migration_applied
loader = MigrationLoader(connection)
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/db/migrations/loader.py", line 49, in __init__
self.build_graph()
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/db/migrations/loader.py", line 184, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/db/migrations/recorder.py", line 60, in applied_migrations
return set(tuple(x) for x in self.migration_qs.values_list("app", "name"))
TypeError: unhashable type: 'bytearray'
I'm using python-3.4, django-1.7.4 and for the SQL connection mysql-connector-python-2.0.2. For this project I've created a virtual environment with the python 3 venv. I host this project on github: https://github.com/pkreker/p_kreker
Thank you in advance!
edit settings.py:
"""
Django settings for p_kreker project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#l)bvja#q45ud2d813g*i+n2=1#kbf#nzqm6()c)dv116pqq^p'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'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 = 'p_kreker.urls'
WSGI_APPLICATION = 'p_kreker.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'NAME': 'p_kreker',
'ENGINE': 'mysql.connector.django',
'USER': 'paul',
'PASSWORD': 'm2aJup2fHYDdArGT',
'OPTIONS': {
'autocommit': True,
},
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'de-de'
TIME_ZONE = 'Europe/Berlin'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
Since the bug headline does not specify "Django", I expect a number of Python 3 newbies will end up here. Note that the hashable/immutable counterpart to "bytearray" is the type "bytes".
>>> b1 = bytearray([1, 2, 3])
>>> s = set()
>>> s.add(b1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'bytearray'
>>> b2 = bytes(b1)
>>> b2
b'\x01\x02\x03'
>>> s.add(b2)
>>>
I think this is likely to be a bug in mysql-connector-python - does it support Django 1.7.4? Your code works fine if you run it with sqlite.
If the project is on an older version of Django for example 1.11.16, try explicit decoding by calling the method .decode("utf-8") in introspection.py file.
if django.VERSION >= (1, 8):
return [
TableInfo(row[0].decode("utf-8"), {'BASE TABLE': 't', 'VIEW': 'v'}.get(row[1].decode("utf-8")))
for row in cursor.fetchall()
]
else:
return [row[0] for row in cursor.fetchall()]
introspection.py file path:
C:\Python27\Lib\site-packages\mysql\connector\django\introspection.py
method prototype:
def get_table_list(self, cursor):
I had this error today. I had created my db as utf8_bin collation, which I assume was the reason for it. Dropped the DB, re-created with utf8_general_ci, ran migrations, and it worked fine.

Django: Collect Static WinError 3

ive got a problem here. When i try to "collectstatic" from manage.py it just kicks me off with following error:
Traceback (most recent call last):
File "C:\Program Files (x86)\JetBrains\PyCharm 3.1.3\helpers\pycharm\django_manage.py", line 23, in <module>
run_module(manage_file, None, '__main__', True)
File "C:\Python34\lib\runpy.py", line 182, in run_module
return _run_module_code(code, init_globals, run_name, mod_spec)
File "C:\Python34\lib\runpy.py", line 96, in _run_module_code
mod_name, mod_spec, pkg_name, script_name)
File "C:\Python34\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:/Users/mszalewski/PycharmProjects/OwnPixel_com\manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 399, in execute_from_command_line
utility.execute()
File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python34\lib\site-packages\django\core\management\base.py", line 242, in run_from_argv
self.execute(*args, **options.__dict__)
File "C:\Python34\lib\site-packages\django\core\management\base.py", line 285, in execute
output = self.handle(*args, **options)
File "C:\Python34\lib\site-packages\django\core\management\base.py", line 415, in handle
return self.handle_noargs(**options)
File "C:\Python34\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 173, in handle_noargs
collected = self.collect()
File "C:\Python34\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 103, in collect
for path, storage in finder.list(self.ignore_patterns):
File "C:\Python34\lib\site-packages\django\contrib\staticfiles\finders.py", line 106, in list
for path in utils.get_files(storage, ignore_patterns):
File "C:\Python34\lib\site-packages\django\contrib\staticfiles\utils.py", line 25, in get_files
directories, files = storage.listdir(location)
File "C:\Python34\lib\site-packages\django\core\files\storage.py", line 250, in listdir
for entry in os.listdir(path):
FileNotFoundError: [WinError 3] Das System kann den angegebenen Pfad nicht finden: 'C:\\Users\\mszalewski\\PycharmProjects\\static\\static'
Process finished with exit code 1
The following is my settings.py:
import os
import os.path
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'OwnPixel_com.urls'
WSGI_APPLICATION = 'OwnPixel_com.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "static", "templates").replace('\\','/')
)
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static-only").replace('\\', '/')
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media").replace('\\', '/')
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "static", "static").replace('\\', '/'),
)
At least my extendes urls.py
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
Iam very sure that its the double backslash in the path (at the end of the error code).
I hope you can help me to fix my problem.
THANKS!!!
Regards, Marvyn
What does your Directory structure actually look like?
I doubt that 'C:\Users\mszalewski\PycharmProjects\static\static' is the folder you're intending to use for the Project specific static files.
My guess is that you want to change
os.path.join(os.path.dirname(BASE_DIR), "static", "static").replace('\\', '/')
to
os.path.join(BASE_DIR, "static", "static")
Or something very similar. And don't worry about the '\\' and '/'. Python will actually get along just fine with some very odd combinations of them in the same path.
Because you are in a virtual directory (assuming you've already activated the virtual env like so : source <*Scripts* or *bin*>/activate), the path that STATIC_ROOT and STATICFILES_DIRS expect are different.
1) STATIC_ROOT is expecting the location of the static files on your local machine (whether that be the cloud server you are serving these files on the computer that you are developing on) --> i.e. something like STATIC_ROOT = 'C:/Users/<user>/Desktop/django_env_folder/mysite/static/mysite'
2) STATICFILES_DIRS on the other hand is expecting the virtual_env path (remember, when you activate your virtual env using the command above, the paths that os.<method>() requires are different (do some debugging to see, try running os.listdir('C:/....') and you will notice different results than expected. SO try something like this for STATICFILES_DIRS --> STATICFILES_DIRS = [
'mysite/static/mysite',
]
** This solution definitely works when serving on localhost, make sure Debug = True in your settings.py.

Categories