UnicodeDecodeError in Django 1.6 static file server - django

I've recently upgraded my project environment to django 1.6. After the upgrade, I found out that all the static files in the existing projects do not work anymore, even if I create a new project following the tutorial, the static file still does not work. Can any one help me out?
Here is my project structure
-mysite
manage.py
-mysite
urls.py
views.py
settings.py
__init__.py
wsgi.py
-static
jqury.js
settings.py looks like this
INSTALLED_APPS = (
...
'django.contrib.staticfiles',
)
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'WorldCup\\templates'),
)
TEMPLATE_CONTEXT_PROCESSORS = [
'django.core.context_processors.static',
'django.contrib.auth.context_processors.auth',
]
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'WorldCup\\static'),
)
print STATICFILES_DIRS
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
I print the staticfiles_dirs, the result is ('G:\django_project\mysite\mysite\static',), which correctly points to my static file folder.
The html file looks like:
{% load staticfiles %}
<script type="text/javascript" src="{% static "WorldCup/jquery-1.10.2.js" %}"
<body>
hello world======{% static "WorldCup/jquery-1.10.2.js" %}=======
</body>
the page displays "hello world======/static/jquery-1.10.2.js=======", which seems correct.
But the Console complained with:
Traceback (most recent call last):
File "D:\Python27\lib\wsgiref\handlers.py", line 85, in run
self.result = application(self.environ, self.start_response)
File "D:\Python27\lib\site-packages\django\contrib\staticfiles\handlers.py", l
ine 68, in __call__
return super(StaticFilesHandler, self).__call__(environ, start_response)
File "D:\Python27\lib\site-packages\django\core\handlers\wsgi.py", line 206, i
n __call__
response = self.get_response(request)
File "D:\Python27\lib\site-packages\django\contrib\staticfiles\handlers.py", l
ine 58, in get_response
return self.serve(request)
File "D:\Python27\lib\site-packages\django\contrib\staticfiles\handlers.py", l
ine 51, in serve
return serve(request, self.file_path(request.path), insecure=True)
File "D:\Python27\lib\site-packages\django\contrib\staticfiles\views.py", line
41, in serve
return static.serve(request, path, document_root=document_root, **kwargs)
File "D:\Python27\lib\site-packages\django\views\static.py", line 61, in serve
content_type, encoding = mimetypes.guess_type(fullpath)
File "D:\Python27\lib\mimetypes.py", line 297, in guess_type
init()
File "D:\Python27\lib\mimetypes.py", line 358, in init
db.read_windows_registry()
File "D:\Python27\lib\mimetypes.py", line 258, in read_windows_registry
for subkeyname in enum_types(hkcr):
File "D:\Python27\lib\mimetypes.py", line 249, in enum_types
ctype = ctype.encode(default_encoding) # omit in 3.x!
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb9 in position 0: ordinal
not in range(128)
[01/Dec/2013 07:42:33] "GET /static/jquery-1.10.2.js HTTP/1.1" 500 59
Even if I change to the image file instead of js file, I still get those errors....

My best guess based on your error message is that you have non-ASCII characters in your Windows registry, and something in the mimetypes module (part of the Python standard library) is choking on that. I assume either the Django statics server, or the Django staticfiles app itself, is calling mimetypes.
This is not a problem with your system per se; if I'm correct in my diagnosis it's clearly a bug in mimetypes.
Here are some options:
You could upgrade to Python 3.3 or 3.4 beta. Django 1.6 is fully compatible with Python 3 and I would be very surprised to see that this bug still exists in Py3 because one of the explicit goals of Py3 was to make unicode encode/decode errors less common.
You could downgrade back to Django 1.5.
You could use a different operating system for development work. Relatively few Python programmers do their dev work in Windows, although the number is not zero either. You are less likely to run into extremely obscure bugs if you use OS X or Linux for development work. That having been said, Windows is an officially supported platform, so if there is a problem with the interaction between CPython and Windows, then that is a CPython bug.
You could try to find exactly what change between 1.5 and 1.6 caused this problem, but that is likely a fool's errand and, assuming it's not an outright bug in Django, will at best result in you having to maintain a fork with your patch for your personal use (not recommended).
You could try to find the offending line in your registry and scrub it, but I don't know how you would go about doing this. You may have a combination of locale settings, the localized version of Windows, non-English installed software or custom MIME types that is causing this problem. Since it seems likely that it is a bug in the mimetypes library and not the fault of your system, you could easily find that the problems in your registry are simply a consequence of some normal function of your computer.
If the problem is with the Django statics server in a way that wouldn't affect your application in production (where the Django statics server, which is only suitable for development, would presumably be disabled) then you could disable the Django statics server and use some other statics serving solution for development. This is inconvenient but would probably work, as long as the problem is with the Django statics server only. To test, set DEBUG to False or otherwise turn off the statics server and run your application -- if it still crashes, then it's not a Django statics server issue; otherwise, it likely is.
Finally, you could try to track down the actual bug and fix it. This is a complex process -- you would need to isolate the bug, see whether it needs to be fixed in the CPython standard library or in Django (I suspect the former), file a report with either of those projects, then write a patch and submit it or get someone else to do likewise. Until it is submitted and accepted, you could theoretically maintain a fork of CPython with the fix applied, but that is a maintenance nightmare.
There is still the possibility that I am outright wrong about the cause and it's not a bug in mimetypes -- in that case you might have more options.

very unfortunetly I have this problem as well. I was using python 3.3, everything works fine. But since my production side is running python 2.7, so I created an a virtualenv with python 2.7.6, and then installed South, debug toolbar, which is the same as my Python3.3 environment. But it just simply not work with python2.7 virtualenv. My Django version is 1.6. So my simple way around this is to switch back to my python3.3.
For more details, my guess would be something related models/database goes wrong. I recall that after a database migration in my virtualenv python2.7 version, this problem appears, while before that everything goes well.
So I would suggest you to run a virtualenv with Python3.3, and debug for the old problem whenever you have more time. Anyway, to save time first. I find Django is really a nice framework, but Python with its multiple packages just have too much buggy stuff that you just do not want to waste your time to go over every one of them.

I have same problem.
Today I have access only to machine, with windows XP.
I've debugged this error and found, that key in windows registry has bad value.
In my case it was: 'BDATuner.���������'.
I hadn't enouth time to edit registry so I temporary add exception to File "D:\Python27\lib\mimetypes.py", line 249, in enum_types
try:
ctype = ctype.encode(default_encoding) # omit in 3.x!
except UnicodeEncodeError, UnicodeDecodeError:
pass
else:
yield ctype
I solved my problems.
I know that patching django code that way is bad, so it's only workaround.
The correct way is to get rid of bad registry values (regedit - next search for this values).

Related

drf-spectacular is using the wrong AutoSchema to generate Swagger

Previously I was using drf-yasg but want to update to use OpenAPI 3. I am trying to switch over to drf-spectacular. Following the instruction, I ran pip install drf-spectacular, I've removed all references to the drf-yasg package, and updated Settings.py as follows:
INSTALLED_APPS = [
...
"drf_spectacular",
]
REST_FRAMEWORK = {
"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
}
When I use the CLI to generate the schema, I get the bellow AssertionError. If anyone has run into this problem before and has any insight, it would be much appreciated!
I'm using Python 3.7, Django 3.0, Django Rest Framework 3.11, and DRF Spectacular 0.10.0.
Traceback (most recent call last):
File "manage.py", line 23, in <module>
main()
File "manage.py", line 19, in main
execute_from_command_line(sys.argv)
File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute
output = self.handle(*args, **options)
File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/drf_spectacular/management/commands/spectacular.py", line 50, in handle
schema = generator.get_schema(request=None, public=True)
File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/drf_spectacular/generators.py", line 187, in get_schema
paths=self.parse(request, public),
File "/opt/anaconda3/envs/dev/lib/python3.7/site-packages/drf_spectacular/generators.py", line 160, in parse
'Incompatible AutoSchema used on View. Is DRF\'s DEFAULT_SCHEMA_CLASS '
AssertionError: Incompatible AutoSchema used on View. Is DRF's DEFAULT_SCHEMA_CLASS pointing to "drf_spectacular.openapi.AutoSchema" or any other drf-spectacular compatible AutoSchema?
Please update the Django Rest Framework 3.11 to 3.12 it will work.
I have the same issue when I had REST_FRAMEWORK two times written for different settings in my settings.py. I moved everything in one variable and error is gone
If the AssertionError is about DRF's ObtainAuthToken then it is most likely an old bug in DRF. This issue was fixed in DRF>=3.12. Prior to that, DRF used a wrong class where it was not supposed to.
drf-yasg seems to not suffer from this upstream bug due to a different injection technique used. drf-spectacular has a mitigation for the bug starting with 0.24.0.
Related GH issue with workaround for older drf-spectacular versions:
https://github.com/tfranzel/drf-spectacular/issues/796#issuecomment-1231464792
Sidenote: If this does not fix your problem and/or it is the same Assertion for some other view, you likely have a misconfigured settings.py. Make sure DEFAULT_SCHEMA_CLASS is properly set as stated in the README. Also make sure you are not shooting yourself in the foot by not setting this also in your production settings file. If the problem still persists, please open an issue on Github and get help there.
Check if you're importing from rest_framework!
Having a
from rest_framework.pagination import PageNumberPagination
was all it took to provoke the error. As soon as I removed the import, things started working again.
This even applies when importing other modules which in turn import from rest_framework. I ended up using the "sting imports" like so:
"DEFAULT_PAGINATION_CLASS": "api.pagination.DefaultPagination",

Problem with migrating a django server (syntax error)

I am trying to make a django server for a sociometric badge (https://github.com/HumanDynamics/openbadge-server) for our university's project. The code (and the whole badge) has been done by someone else and I have not myself changed anything, I am simply trying to get it to work. I am able to build the server but when trying to migrate or create a superuser, I get a syntax error. I've been trying to troubleshoot it by myself but I have very limited knowledge of python, django and Ubuntu so I'm probably missing something.
The error implies an error in the line 44 of /usr/local/lib/python2.7/site-packages/pkgconf/init.py but I cannot find the file so I cannot check it. In fact, the whole site-packages folder is empty so I wonder if I have installed modules in a wrong way? The code is written in python2.7 (Which I cannot change as it is not my code) so I also wonder if the python2.7 being EOL could cause issues? It has already broken some parts, mainly how to get some of the dependencies.
The code and docker files used in this project can be found here: https://github.com/HumanDynamics/openbadge-server
The dependency versions should be fine, the Django version should be compatible with Python2.7 and same for other modules. I've tried changing the versions around but to no avail. Down here is the requirement texts
Django==1.8.4
Fabric==1.10.2
django-grappelli==2.7.1
simplejson==3.8.0
MarkupSafe==0.23
django-pipeline==1.5.4
djangorestframework==3.2.3
djangorestframework-expiring-authtoken==0.1.1
pytz==2015.7
python-dateutil==2.5.3
jsonfield==1.0.3
django-controlcenter===0.2.6
# Configuration
django-environ==0.4.1
# Python-PostgreSQL Database Adapter
psycopg2==2.7.3.2
# Unicode slugification
awesome-slugify==1.6.5
# Import and export using the admin tool
# Using tablib 0.12.1. Newer versions break the import-export add-on
tablib==0.12.1
django-import-export==1.0.0
coverage==4.3.1
django-coverage-plugin==1.3.1
Sphinx==1.5.1
django-extensions==1.7.5
Werkzeug==0.11.15
django-test-plus==1.0.16
factory-boy==2.8.1
django-debug-toolbar==1.6
# improved REPL
ipdb==0.10.1
pytest-django==3.1.2
pytest-sugar==0.8.0
This is the error. From my limited knowledge, I'd gather that it doesn't find the files from /usr/local/lib/python2.7/site-packages/ but it is completely empty, the dependencies are either installed locally or to dist-packages. Someone earlier said that it was a python3 problem but nothing should be Python3. Could it also be a docker version problem if the build somehow installs wrong things?
Starting openbadge-server_postgres_1 ... done
Postgres is up - continuing...
Traceback (most recent call last):
File "manage.py", line 23, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
django.setup()
File "/usr/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/usr/local/lib/python2.7/site-packages/django/apps/config.py", line 86, in create
module = import_module(entry)
File "/usr/local/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/usr/local/lib/python2.7/site-packages/controlcenter/__init__.py", line 1, in <module>
from .dashboards import Dashboard # NOQA
File "/usr/local/lib/python2.7/site-packages/controlcenter/dashboards.py", line 10, in <module>
from . import app_settings
File "/usr/local/lib/python2.7/site-packages/controlcenter/app_settings.py", line 1, in <module>
from pkgconf import Conf
File "/usr/local/lib/python2.7/site-packages/pkgconf/__init__.py", line 44
class Conf(metaclass=ConfMeta):
^
SyntaxError: invalid syntax
I will provide information to best of my abilities.
Fixed the issue by adding django-pkgconf==0.3.0 to the requirements. While the requirements did not have the package at all, it was still installed (and used) through other packages and it installed version 0.4.0 which does not support Python 2.7.
Weird thing is that I could not find a trace where it was installed if I installed it without having it on requirements so even when I manually installed 0.3.0, it would still use 0.4.0 (despite seemingly not having it installed) so in order to get it to work it had to be installed through the docker build.

wkhtmltopdf subprocess error using django wrapper, but not in shell

I'm using wkhtmltopdf together with the django-wkhtmltopdf wrapper to create a .pdf of a template.
I'm using the example from the django-wkhtmltopdf documentation (though I eventually want more than just a static template):
url(r'^pipeline/snapshot/$', PDFTemplateView.as_view(
template_name='pdf/pipeline_snapshot.html',
filename='my_pdf.pdf'), name='pdf'),
And I'm getting the error:
Traceback:
File "/home/pluscitizen/webapps/odin/lib/python2.7/django/core/handlers/base.py" in get_response
140. response = response.render()
File "/home/pluscitizen/webapps/odin/lib/python2.7/django/template/response.py" in render
105. self.content = self.rendered_content
File "/home/pluscitizen/webapps/odin/lib/python2.7/django_wkhtmltopdf-1.2.2-py2.7.egg/wkhtmltopdf/views.py" in rendered_content
144. footer_filename=footer_filename)
File "/home/pluscitizen/webapps/odin/lib/python2.7/django_wkhtmltopdf-1.2.2-py2.7.egg/wkhtmltopdf/views.py" in convert_to_pdf
103. return wkhtmltopdf(pages=[filename], **cmd_options)
File "/home/pluscitizen/webapps/odin/lib/python2.7/django_wkhtmltopdf-1.2.2-py2.7.egg/wkhtmltopdf/utils.py" in wkhtmltopdf
92. return check_output(ck_args, **ck_kwargs)
File "/usr/local/lib/python2.7/subprocess.py" in check_output
575. raise CalledProcessError(retcode, cmd, output=output)
Exception Type: CalledProcessError at /pipeline/snapshot/
Exception Value: Command '['wkhtmltopdf', '--encoding', u'utf8', '--quiet', '/tmp/wkhtmltopdfVaAKrX.html', '-']' returned non-zero exit status 127
However, when I run the same command, with the same file, from the Django shell
>>> subprocess.check_output(['wkhtmltopdf', '--encoding', u'utf8', '--quiet', '/tmp/wkhtmltopdfSGFfYh.html', '-'])
everything runs fine. Ditto for:
>>> wkhtmltopdf(['/tmp/wkhtmltopdfSGFfYh.html'], **{})
So, figuring that the difference must be in the whole shell situation, I've tried adding a shell=True to the call to subprocess within django-wkhtmltopdf (I know it's a security problem), but no luck there. Probably because I have no idea what's really going on.
I saw somewhere saying that the problem might have to do with PATHs not being set up properly, but then I don't understand why Django's shell is not having issues with this.
This entire process has been incredibly taxing, and now that I'm so close, I'm finally turning to SO for an answer.
EDIT: I have tried running the subprocess directly in a view, and it returns the same error, which I guess means that the shell and the server aren't necessarily both running from the same environment?
FIXED: Solved, and the answer by sparks led me on the way. I decided to look at the logs (duh) output by the django app on the server, and noticed that before the traceback, I'm getting the actual output of the command:
wkhtmltopdf: error while loading shared libraries: libwkhtmltox.so.0: cannot open shared object file: No such file or directory
Which seems to imply that it's not finding the libraries I have in /home/user/lib. When I explicitly added these to the WKHTMLTOPDF_ENV variable in settings.py, everything worked swimmingly.
exit status 127
This means that the command you're trying to run can't be found. It is an error in the environment of your process.
I would suggest looking at the contents of sys.path in python and comparing that to the PATH environment variable, or compared to sys.path in the django console.
More specifically, add this to settings.py:
WKHTMLTOPDF_ENV = {'FONTCONFIG_PATH': '/etc/fonts'}

Error "sqlserver_ado isn't an available database backend" (PyISAPIe on IIS)

I'm having problems connecting my Django project to SQL Server 2008 when using IIS to serve Django and django-mssql to handle transactions. I am using IIS 7 and 64 bit ActivePython 2.7.
Here is my list of installed packages:
Django==1.4.5
distribute==0.6.19
django-mssql==1.2
pypm==1.3.4
pythonselect==1.3
pywin32==214
virtualenv==1.6.1
wsgiref==0.1.2
And here is the last bit of the stack trace:
File "C:\Python27\lib\site-packages\django\db\__init__.py", line 40, in
backend = load_backend(connection.settings_dict['ENGINE'])
File "C:\Python27\lib\site-packages\django\db\__init__.py", line 34, in __getattr__
return getattr(connections[DEFAULT_DB_ALIAS], item)
File "C:\Python27\lib\site-packages\django\db\utils.py", line 92, in __getitem__
backend = load_backend(db['ENGINE'])
File "C:\Python27\lib\site-packages\django\db\utils.py", line 51, in load_backend
raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: 'sqlserver_ado' isn't an available database backend.
Try using django.db.backends.sqlserver_ado instead.
Error was: DLL load failed: The specified module could not be found.
If I add the sqlserver_ado folder to C:\Python27\Lib\site-packages\django\db\backends and change my database settings in settings.py from 'ENGINE': 'sqlserver_ado', to 'ENGINE': 'django.db.backends.sqlserver_ado',, then I get a slightly different stack trace.
File "C:\Python27\lib\site-packages\django\db\backends\sqlserver_ado\base.py", line 6, in
import dbapi as Database
File "C:\Python27\lib\site-packages\django\db\backends\sqlserver_ado\dbapi.py", line 49, in
import pythoncom
File "C:\Python27\lib\site-packages\pythoncom.py", line 2, in
import pywintypes
File "C:\Python27\lib\site-packages\win32\lib\pywintypes.py", line 124, in
__import_pywin32_system_module__("pywintypes", globals())
File "C:\Python27\lib\site-packages\win32\lib\pywintypes.py", line 64, in __import_pywin32_system_module__
import _win32sysloader
ImportError: DLL load failed: The specified module could not be found.
If I connect to a sqlite database instead of SQL Server, the application works fine.
If I run the project using the development server, connecting to SQL Server works fine.
So it seems the problem is the combination of IIS / PyISAPIe and django_mssql.
Several other questions have mentioned similar issues. Each of these were solved by somehow getting python dlls on the system path. I tried (both by checking the path and copying the files into c:\python2.7, but I get the same error.
https://stackoverflow.com/questions/13965251/django-error-in-apache-2-2-database-backend-fails-in-production-but-successful
pywintypes27.dll not found using Apache, Django, pywin32, Python2.7 and mod_wsgi
http://code.google.com/p/django-mssql/issues/detail?id=107
For a last bit of info, here is sys.path for the development server version and the IIS / PyISAPIe version.
Development (works):
C:\Users\Administrator\Desktop\django test C:\Python27\python27.zip C:\Python27\DLLs C:\Python27\lib C:\Python27\lib\plat-win C:\Python27\lib\lib-tk C:\Python27 C:\Users\Administrator\AppData\Roaming\Python\Python27\site-packages C:\Python27\lib\site-packages C:\Python27\lib\site-packages\win32 C:\Python27\lib\site-packages\win32\lib C:\Python27\lib\site-packages\Pythonwin C:\Python27\lib\site-packages\setuptools-0.6c11-py2.7.egg-info
IIS (fails):
C:\PyISAPIe C:\Windows\system32\python27.zip C:\Python27\Lib C:\Python27\DLLs C:\Python27\Lib\lib-tk c:\windows\system32\inetsrv C:\Python27 C:\Python27\lib\site-packages C:\Python27\lib\site-packages\win32 C:\Python27\lib\site-packages\win32\lib C:\Python27\lib\site-packages\Pythonwin C:\Python27\lib\site-packages\setuptools-0.6c11-py2.7.egg-info c:\inetpub\PyApp
Any tips or suggestions of where to go from here would be appreciated. I'm going to try out normal (i.e. non-Active) Python next to see if that makes a difference.
Installing 64 bit python from scratch and following the advice here worked. The problem must have been some goofiness with Active Python.
There was one thing I did notice that may be helpful.
With a normal installation of python and pywin32 (using the executables from the linked sites), C:\Python27\Lib\site-packages contained a folder named pywin32_system32 which contained the executables that needed to be copied to C:\Python27 to solve the problem.
With the Active Python installation, this directory did not exist.
I also noticed that the directories that are there for both installation methods (win32, win32com, and win32comext) contain slightly different files.
I hope this saves someone else some pain in the future.

pycharm - how to "run" a project with add_to_builtins?

i am using pycharm with django. When i do the runserver command, my project starts up and everything is fine.
if i use the pycharm run command - that green arrow at the top - then i get problems.
The problems are:
runnerw.exe C:\development\python\python.exe manage.py runserver 127.0.0.1:8000
Traceback (most recent call last):
File "manage.py", line 11, in
import settings
File "C:\development\PycharmProjects\dumpstown\settings.py", line 185, in
add_to_builtins('gravatar.templatetags.gravatar')
File "C:\development\python\lib\site-packages\django\template\base.py", line 1017, in add_to_builtins
builtins.append(import_library(module))
File "C:\development\python\lib\site-packages\django\template\base.py", line 963, in import_library
raise InvalidTemplateLibrary("ImportError raised loading %s: %s" % (taglib_module, e))
django.template.base.InvalidTemplateLibrary: ImportError raised loading
gravatar.templatetags.gravatar: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
Process finished with exit code 1
And stem from my use of add_to_builtins here: (this is in the settings.py file)
#gravatar stuff here.
add_to_builtins('gravatar.templatetags.gravatar')
I know this is the problem, because if i remove this line in the settings.py file? everything works fine.
Is there a way to remedy this problem for pycharm?
You need to set your Django settings module in Settings | Django Support | Settings
http://www.jetbrains.com/pycharm/webhelp/django-support.html
UPDATED
The problem with django-gravatar is that it's templatetags import django.contrib.auth.models.User which relies on settings module while setting module is loaded in Django by DJANGO_SETTINGS_MODULE environment variable, which is set internally by execute_manager function call in manage.py, which is executed AFTER import of settings. So when you use undocumented add_to_builtins feature just in settings.py at that point you have no DJANGO_SETTINGS_MODULE env variable set. So that is not a problem of PyCharm, but a problem of unset environment variable and usage of undocumented Django feature add_to_builtin.
When I ran the same project from Unix console I get the same error.
Probably you have DJANGO_SETTINGS_MODULE set in your environment if it works from console.
So to make it work in PyCharm you need to set up the variable in Django run configuration.
You can read here about that (see Environment variable section).
As i answered here: https://stackoverflow.com/a/11299516/1061426
pycharm is broken and doesn't work with add_to_builtins. The two obvious solutions are:
don't use pycharm, use some free django plugins for eclipse, or old school text editing?
use pycharm, just don't use add_to_builtins. This is the route i've gone down - it is annoying fixing all the template's to import a module, but it was a lot simpler in my case than the hassle of porting across to a new IDE.