Django unittests fail because of fixture load issue - python

I use fixtures for prepopulating some simple auxilary data.
I can successfully load fixtures using manage.py loaddata fixtures/initial_data.json.
A problem appears when I try to run a unit test. It gives me the following error:
File "/usr/local/lib/python3.4/dist-packages/django/db/models/query.py", line 600, in _update
return query.get_compiler(self.db).execute_sql(CURSOR)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/sql/compiler.py", line 1004, in execute_sql
cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/sql/compiler.py", line 786, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.4/dist-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/local/lib/python3.4/dist-packages/django/utils/six.py", line 549, in reraise
raise value.with_traceback(tb)
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: Problem installing fixture '/opt/prjoect/myapp/fixtures/initial_data.json': Could not load myapp.SomeModel(pk=1): relation "myapp_somemodel" does not exist
LINE 1: UPDATE "myapp_somemodel" SET "name" = 'M' WHERE "myapp_somemodel"."id" = 1
Following tables are presented in regular database. This fixture doesn't have foreign keys, only simple tables, with key and other values.
I have only one initial_migration in my migrations module.
Where is the problem? I have no idea what could be the root cause.
I use Django 1.7, python 3.4, Postrgesql, Ubuntu 14.04

It seems your fixture is trying to update an object with id=1:
LINE 1: UPDATE "myapp_somemodel" SET "name" = 'M' WHERE "myapp_somemodel"."id" = 1
and this object does not exist:
Could not load myapp.SomeModel(pk=1)...
Do you have an object of myapp_somemodel1 with id/pk = 1 ?
Maybe you had it when you generate the fixture, and after you've deleted it. You could try to do in the shell:
from myapp.models import somemodel
new_object = Somemodel(id=1, name='anything')
new_object.save()
And then try to load the fixture again

Related

How to access tables from a different schema in oracle 11g using django?

I have a user named mi_abc in oracle 11g.
The user do not have any table in the database but has access to all the tables in another schema sch_abc.
When I run a normal select query from sqldeveloper on the sch_abc schema from mi_abc, it works perfectly fine, but when I use django, I am always getting the error:-
django.db.utils.DatabaseError: ORA-00942: table or view does not exist
I tried to set the db_table = sch_abc.tableName and also set db_table = tableName but both gives me the same error. Any clue how to resolve this?
TRACE:-
Traceback (most recent call last):
File "C:\xxx\xxx\xxx\xxx\xxx\xxx\xxxx\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
response = get_response(request)
File "C:\xxx\xxx\xxxx\xxxx\xxxx\Python\Python37\lib\site-packages\django\utils\deprecation.py", line 142, in __call__
response = self.process_response(request, response)
File "C:\xxxx\xxxx\xxx\xxx\xxx\Python\Python37\lib\site-packages\django\contrib\sessions\middleware.py", line 58, in process_response
request.session.save()
File "C:\xxx\xxxx\xxxx\xxxx\xxxxx\Python\Python37\lib\site-packages\django\contrib\sessions\backends\db.py", line 81, in save
return self.create()
File "C:\xxxx\xxxxx\xxxx\xxxx\xxxxx\Python\Python37\lib\site-packages\django\contrib\sessions\backends\db.py", line 50, in create
self._session_key = self._get_new_session_key()
File "C:\xxxx\xxxxx\xxxxx\xxxxx\xxxx\Python\Python37\lib\site-packages\django\contrib\sessions\backends\base.py", line 164, in _get_new_session_key
if not self.exists(session_key):
File "C:\xxx\xxx\xxx\xxx\xxx\Python\Python37\lib\site-packages\django\contrib\sessions\backends\db.py", line 46, in exists
return self.model.objects.filter(session_key=session_key).exists()
File "C:\xxx\xxx\xxx\xxx\xxx\Python\Python37\lib\site-packages\django\db\models\query.py", line 673, in exists
return self.query.has_results(using=self.db)
File "C:\xxx\xxx\xxx\xxx\xxx\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 517, in has_results
return compiler.has_results()
File "C:\xxx\xxx\xxx\xxx\xxx\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 858, in has_results
return bool(self.execute_sql(SINGLE))
File "C:\xxx\xxx\xxx\xxx\xxx\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 899, in execute_sql
raise original_exception
File "C:\xxx\xxx\xxx\xxx\xxx\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 889, in execute_sql
cursor.execute(sql, params)
File "C:\xxx\xxx\xxx\xxx\xxx\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\xxx\xxx\xxx\xxx\xxx\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\xxx\xxx\xxx\xxx\xxx\Python\Python37\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\xxx\xxx\xxx\xxx\xxx\Python\Python37\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\xxx\xxx\xxx\xxx\xxx\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\xxx\xxx\xxx\xxx\xxx\Python\Python37\lib\site-packages\django\db\backends\oracle\base.py", line 497, in execute
return self.cursor.execute(query, self._param_generator(params))
django.db.utils.DatabaseError: ORA-00942: table or view does not exist
Well, I resolved the issue and let me tell you there is no straight way to do it in django. The problem with my application was, I was using the authetication features of django and also session handling. All these tables are created by django directly on the initial migration. So, there is no existence of them in the models.py file that you can simply append the schema name and ask your application to connect to the table of that schema.
What I ended up doing is, I created private synonyms to all the tables of the other schema which actually contained those tables. If you do this, you don't have to change anything in your django code. Your application will simply work because oracle will do the dirty work of actually connecting to the proper table. You will merely call the table in your application as if its your own. In this way when django looks for tables like django_session, auth_user etc, it simply queries it like it always does and oracle redirects it to the actual tables present in another schema.
Hope this helps people who face this issue in the future.
This is by no means officially supported, but this works in Postgres:
class Meta:
managed = False
db_table = 'schema\".\"table'
It took some trial and error for Postgres, but you can probably do something similar for Oracle. This is because the Postgres engine quotes object names, and this fakes the quoting mechanism out.
UPDATE:
After doing some digging, I found this for Oracle (modified for Python 3):
class Meta:
db_table = '"SCHEMA"."TABLE_NAME"'
Source: https://code.djangoproject.com/ticket/14136
I would recommend keeping managed = False unless you really know what you're doing. Good luck!
You can set the required schema, before executing the command. and then go back to public schema once the queryset is processed.
from django.db import connection
connection.set_schema(schema_name)

django.db.utils.IntegrityError: FOREIGN KEY constraint failed while executing LiveServerTestCases through Selenium and Python Django

I can run all unit tests successfully, I can even run selenium tests successfully if I run an independent server, but when I try to use LiveServerTestCases to test everything in a self-contained manner, each LiveServerTestCase test ends with the following error after completing the tearDown function:
File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\db\backends\base\base.py", line 239, in _commit
return self.connection.commit()
django.db.utils.IntegrityError: FOREIGN KEY constraint failed
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\test\testcases.py", line 209, in __call__
self._post_teardown()
File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\test\testcases.py", line 908, in _post_teardown
self._fixture_teardown()
File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\test\testcases.py", line 943, in _fixture_teardown
inhibit_post_migrate=inhibit_post_migrate)
File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\core\management\__init__.py", line 148, in call_command
return command.execute(*args, **defaults)
File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\core\management\base.py", line 353, in execute
output = self.handle(*args, **options)
File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\core\management\commands\flush.py", line 80, in handle
emit_post_migrate_signal(verbosity, interactive, database)
File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\core\management\sql.py", line 51, in emit_post_migrate_signal
**kwargs
File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\dispatch\dispatcher.py", line 175, in send
for receiver in self._live_receivers(sender)
File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\dispatch\dispatcher.py", line 175, in <listcomp>
for receiver in self._live_receivers(sender)
File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\contrib\auth\management\__init__.py", line 79, in create_permissions
Permission.objects.using(using).bulk_create(perms)
File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\db\models\query.py", line 471, in bulk_create
obj_without_pk._state.db = self.db
File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\db\transaction.py", line 212, in __exit__
connection.commit()
File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\db\backends\base\base.py", line 261, in commit
self._commit()
File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\db\backends\base\base.py", line 239, in _commit
return self.connection.commit()
File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\db\utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\db\backends\base\base.py", line 239, in _commit
return self.connection.commit()
django.db.utils.IntegrityError: FOREIGN KEY constraint failed
I'm pretty sure I don't have any errors in my database models, as all the unit tests run fine and the selenium tests run fine when I fire up a seperate server instance to run in parallel, so I'm guessing it has to do with selenium?
I've tried using the Chrome webdriver, IE webdriver and Firefox webdriver. Same results.
It doesn't appear to be related to my database as the error only occurs for LiveServerTestCases.
Environment Details
Django version 2.1
SQLite3 version 3.20.0
Some more information regarding the Django version, Database type and version along with your code trials would have helped us to debug this issue in a better way.
However, this error message...
File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\core\management\sql.py", line 51, in emit_post_migrate_signal **kwargs
.
File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\db\backends\base\base.py", line 239, in _commit
return self.connection.commit()
django.db.utils.IntegrityError: FOREIGN KEY constraint failed
...implies that an IntegrityError was raised while attempting to save an existing model instance.
As per Django 2.0 release notes:
Foreign key constraints are now enabled on SQLite: This was a backwards-incompatible change (IntegrityError: FOREIGN KEY constraint failed) if attempting to save an existing model instance that’s violating a foreign key constraint.
Foreign Keys are now created with DEFERRABLE INITIALLY DEFERRED instead of DEFERRABLE IMMEDIATE. So the tables may need to be rebuilt to recreate foreign keys with the new definition, particularly if you’re using a pattern as follows;
from django.db import transaction
with transaction.atomic():
Book.objects.create(author_id=1)
Author.objects.create(id=1)
If you don’t recreate the foreign key as DEFERRED, the first create() would fail as the foreign key constraints are enforced.
#dirkgroten in this discussion provided an example as follows:
Look for patterns like this in your code:
# in pagetree/models.py, line 810
#classmethod
def create_from_dict(cls, d):
return cls.objects.create() # what happens to d by the way?
This will definitely fail with a ForeignKey constraint error since a PageBlock must have section, so you can't call create without first assigning it.

Unknown column '' in 'field list'. Django

I'm using Django 1.9 and MySQL. I want to rename a field in my model. Let's look at model Choice from the Django getting started tutorial.
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length = 200)
votes = models.IntegerField(default=0)
So, I want to rename the votes field to votes_count. I created an empty migration and add to operations following line:
migrations.RenameField (
model_name='choice',
old_name='votes',
new_name='votes_count',
),
After python manage.py migrate, the field in the database table was renamed. But when I tried to use this model
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id);
try:
selected = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {
'question':question,
'error_message':"You didn't select a choice."
})
else:
selected.votes_count += 1
selected.save()
return HttpResponseRedirect(reverse('polls:results', args=(question_id)))
I got:
Unknown column 'polls_choice.votes' in 'field list
Traceback:
File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)
File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/backends/mysql/base.py" in execute
112. return self.cursor.execute(query, args)
File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/cursors.py" in execute
226. self.errorhandler(self, exc, value)
File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/connections.py" in defaulterrorhandler
36. raise errorvalue
File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/cursors.py" in execute
217. res = self._query(query)
File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/cursors.py" in
_query
378. rowcount = self._do_query(q)
File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/cursors.py" in
_do_query
341. db.query(q)
File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/connections.py" in query
280. _mysql.connection.query(self, query)
The above exception ((1054, "Unknown column 'polls_choice.votes' in 'field list'")) was the direct cause of the following exception:
File "/home/verdigo/venv/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/verdigo/venv/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "./polls/views.py" in vote
23. selected = question.choice_set.get(pk=request.POST['choice'])
File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/models/manager.py" in manager_method
122. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/models/query.py" in get
381. num = len(clone)
File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/models/query.py" in __len__
240. self._fetch_all()
File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/models/query.py" in _fetch_all
1074. self._result_cache = list(self.iterator())
File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/models/query.py" in __iter__
52. results = compiler.execute_sql()
File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/models/sql/compiler.py" in execute_sql
848. cursor.execute(sql, params)
File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
79. return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)
File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/utils.py" in
__exit__
95. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/verdigo/venv/lib/python3.4/site-packages/django/utils/six.py" in reraise
685. raise value.with_traceback(tb)
File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)
File "/home/verdigo/venv/lib/python3.4/site-packages/django/db/backends/mysql/base.py" in execute
112. return self.cursor.execute(query, args)
File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/cursors.py" in execute
226. self.errorhandler(self, exc, value)
File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/connections.py" in defaulterrorhandler
36. raise errorvalue
File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/cursors.py" in execute
217. res = self._query(query)
File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/cursors.py" in
_query
378. rowcount = self._do_query(q)
File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/cursors.py" in
_do_query
341. db.query(q)
File "/home/verdigo/venv/lib/python3.4/site-packages/MySQLdb/connections.py" in query
280. _mysql.connection.query(self, query)
Exception Type: OperationalError at /polls/1/vote/
Exception Value: (1054, "Unknown column 'polls_choice.votes' in 'field list'")
It looks as if you created and ran a migration to rename the model field from votes to votes_count, but did not update the model at the same time.
When the Django tries to fetch the model from the db, it tries to select the votes column because you still have a votes field in your models, and you get the error because the column doesn't exist in the database.
Creating a manual migration isn't normally necessary. Usually, you would rename the model field, run makemigrations, then run migrate. The advantage of letting Django create the migration is that you can be confident that the database is in sync with your models after you have run migrate.
Cause: This error occurs when a new one-to-many foreign key is created, pointing to the model with the forkey field and then generating the table
.
Solution: This problem can be solved by directly deleting the database and rebuilding it.
1: drop database database table;
2, re-create after deletion, before the code created, run directly
This is an issue that has persisted with me and lead me down a lot of rabbit holes dropping tables etc. A simple solution I have found is answering "N" when django asks you if you are renaming a field of that model (when running makemigrations). What that then essentially performs is a deletion of your previous field and creates the new field. Be careful as you may lose data on existing field so this works with fields which are either new or relatively easy to 'refill' their data required. You may need to run --fake if you get an error with regards to not being able to 'drop field' when migrating after makemigrations.
Update:
I did the above for a Boolean field and my data was kept. Even though I said N, it seems as if it is essentially a renaming.

Postgres function json_array_elements does not found while django's tests

I have class method in django model which is using json_array_elements function.
In case when it performs by browser it works fine.
But in tests it fails.
python manage.py test
Traceback (most recent call last):
File "path_to_project/dj_server/model_animations/tests.py", line 94, in test_cteating
response_first = model_animations.views.get_animations_list(request, groupid)
File "path_to_project/dj_server/model_animations/views.py", line 37, in get_animations_list
for model_anim in listArray:
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 1535, in __iter__
query = iter(self.query)
File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 76, in __iter__
self._execute_query()
File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 90, in _execute_query
self.cursor.execute(self.sql, self.params)
File "/Library/Python/2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/Library/Python/2.7/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Library/Python/2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
ProgrammingError: function json_array_elements(text) does not exist
LINE 1: ...on_name FROM model_animations_model, json_array...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
in models.py
#classmethod
def animations_list(self, group_id):
if group_id:
try:
listArray = ModelAnimationList.objects.raw(('SELECT * FROM model_animations_model, json_array_elements(animated_groups) AS data WHERE \'"%s"\' = data::text' %group_id))
return listArray
except:
pass
return None
in views.py
def get_animations_list(request, group_id):
...
listArray = ModelAnimationList.animations_list(group_id)
if listArray:
for model_anim in listArray:
if model_anim:
anim_dict = { 'a_id' : model_anim.id, 'a_name' : model_anim.animation_name }
result_anim_list.append(anim_dict)
...
in tests.py
request = HttpRequest()
response_first = model_animations.views.get_animations_list(request, groupid)
Installed:
python 2.7
Django 1.7.1
Postgres 9.3.5
psycopg2 2.5.4
Mac 10.10 yosemite
Mistake in query json_array_elements(animated_groups)
Needs change to this:
json_array_elements(animated_groups::json)
Postgres JSON processing functions such as json_array_elements(animated_groups::json), jsonb_array_elements(animated_groups::jsonb) will take json or jsonb values.
Because postgres JSON field(animated_groups) are store as text format or binary format.
so we need to convert the type by using either ::json or ::jsonb it give the json or jsonb format
check here

Django SYNCDB failes when adding super-user (Windows 7, mySQL, Django 1.2.4, mySQL 5.5)

syncdb fails when creating super user
Django: v 1.2.4
Python: 2.6
MySQL Server: 5.5
Windows 7
Extra: MySQL-Python v1.2.3
What steps will reproduce the problem?
1. install the above programs
2. create a project
3. run syncdb
Note: I have installed mySQL to support UTF 8. I also create the mysite_db database using CREATE DTABASE mysite_db CHARACTER SET = UTF8;
What is the expected output? What do you see instead?
syncdb create the required tables as follows:
C:\DjangoProjects\mysite>python manage.py syncdb
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_site
You just installed Django's auth system, which means you don't have any superuse
rs defined.
Would you like to create one now? (yes/no):
I select 'YES' and get the following error:
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "C:\Python26\lib\site-packages\django\core\management\__init__.py", line
438, in execute_manager
utility.execute()
File "C:\Python26\lib\site-packages\django\core\management\__init__.py", line
379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python26\lib\site-packages\django\core\management\base.py", line 191,
in run_from_argv
self.execute(*args, **options.__dict__)
File "C:\Python26\lib\site-packages\django\core\management\base.py", line 220,
in execute
output = self.handle(*args, **options)
File "C:\Python26\lib\site-packages\django\core\management\base.py", line 351,
in handle
return self.handle_noargs(**options)
File "C:\Python26\lib\site-packages\django\core\management\commands\syncdb.py"
, line 103, in handle_noargs
emit_post_sync_signal(created_models, verbosity, interactive, db)
File "C:\Python26\lib\site-packages\django\core\management\sql.py", line 182,
in emit_post_sync_signal
interactive=interactive, db=db)
File "C:\Python26\lib\site-packages\django\dispatch\dispatcher.py", line 172,
in send
response = receiver(signal=self, sender=sender, **named)
File "C:\Python26\lib\site-packages\django\contrib\auth\management\__init__.py
", line 44, in create_superuser
call_command("createsuperuser", interactive=True)
File "C:\Python26\lib\site-packages\django\core\management\__init__.py", line
166, in call_command
return klass.execute(*args, **defaults)
File "C:\Python26\lib\site-packages\django\core\management\base.py", line 220,
in execute
output = self.handle(*args, **options)
File "C:\Python26\lib\site-packages\django\contrib\auth\management\commands\cr
eatesuperuser.py", line 71, in handle
User.objects.get(username=default_username)
File "C:\Python26\lib\site-packages\django\db\models\manager.py", line 132, in
get
return self.get_query_set().get(*args, **kwargs)
File "C:\Python26\lib\site-packages\django\db\models\query.py", line 342, in g
et
num = len(clone)
File "C:\Python26\lib\site-packages\django\db\models\query.py", line 80, in __
len__
self._result_cache = list(self.iterator())
File "C:\Python26\lib\site-packages\django\db\models\query.py", line 271, in i
terator
for row in compiler.results_iter():
File "C:\Python26\lib\site-packages\django\db\models\sql\compiler.py", line 67
7, in results_iter
for rows in self.execute_sql(MULTI):
File "C:\Python26\lib\site-packages\django\db\models\sql\compiler.py", line 73
2, in execute_sql
cursor.execute(sql, params)
File "C:\Python26\lib\site-packages\django\db\backends\util.py", line 15, in e
xecute
return self.cursor.execute(sql, params)
File "C:\Python26\lib\site-packages\django\db\backends\mysql\base.py", line 86
, in execute
return self.cursor.execute(query, args)
File "C:\Python26\lib\site-packages\MySQLdb\cursors.py", line 175, in execute
if not self._defer_warnings: self._warning_check()
File "C:\Python26\lib\site-packages\MySQLdb\cursors.py", line 89, in _warning_
check
warn(w[-1], self.Warning, 3)
_mysql_exceptions.Warning: Incorrect string value: '\xED' for column 'username'
at row 1
What version of the product are you using? On what operating system?
Django: v 1.2.4
Python: 2.6
MySQL Server: 5.5
Windows 7
Extra: MySQL-Python v1.2.3
Please provide any additional information below.
I also have mySQL C++ and ODBC database connectors installed.
Any help is greatly appreciated.
Looks like you have unicode characters somewhere in your models.py or a fixture. Convert the files to UTF-8 and add a comment as the very first line:
#coding-utf-8
Also, before unicode strings add u, like this:
name = CharField(maxlength=255, default=u"утф-8 строка");
It looks like your login on your development machine has a unicode character in it, and when the createsuperuser.py module looks for a User object with that username, it is barfing because MySQL isn't expecting those characters. You can either change the collation settings on your MySQL tables to accept UTF-8 or use a username that doesn't have unicode characters (which isn't a very nice option).
The real failure in the traceback starts in createsuperuser.py on line 71, and it stems from line 59 here:
try:
default_username = getpass.getuser().replace(' ', '').lower()
except (ImportError, KeyError):
# KeyError will be raised by os.getpwuid() (called by getuser())
# if there is no corresponding entry in the /etc/passwd file
# (a very restricted chroot environment, for example).
default_username = ''
# Determine whether the default username is taken, so we don't display
# it as an option.
if default_username:
try:
User.objects.get(username=default_username)
except User.DoesNotExist:
pass
else:
default_username = ''
It's getting your username via getpass and then trying to look that up in the User table.

Categories