Getting Started with Tastypie: no such table: myapp_entry - django

Just like the title of the page says, I'm Getting Started with Tastypie by following the linked tutorial. But when I try to load /api/entry/?format=json, I get HTTP 500 response, with this error message:
no such table: myapp_entry
When I look in sqlite3, indeed, there's no such table.
Here's how I followed the tutorial:
$ django-admin startproject mysite
$ cd mysite
$ django-admin startapp myapp
I created/edited myapp/models.py, myapp/api.py and mysite/urls.py as specified in the tutorial, and added 'tastypie' to my INSTALLED_APPS in mysite/settings.py.
Note: It wasn't clear to me which urls.py file to edit or create, so I edited the existing one in mysite. So now it looks like this:
from django.conf.urls import url, include
from myapp.api import EntryResource
from django.contrib import admin
entry_resource = EntryResource()
urlpatterns = [
url(r'^admin/', admin.site.urls),
# url(r'^blog/', include('myapp.urls')),
url(r'^api/', include(entry_resource.urls)),
]
I commented out the 'blog' line, because it caused the error ImportError: No module named 'myapp.urls'. I think this is the step I'm stuffing up, but when I tried putting the tutorial code in myapp/urls.py instead, I got a 404 when I tried loading the page, and when I then tried adding url(r'^blog/', include('myapp.urls')) to mysite/urls.py, I got a stack overflow. So I've gone back to the code as shown above.
To be clear, here's what my file structure looks like now:
$ find . -type f -not -name '*.pyc'
./manage.py
./myapp/__init__.py
./myapp/views.py
./myapp/models.py
./myapp/tests.py
./myapp/admin.py
./myapp/apps.py
./myapp/migrations/__init__.py
./myapp/api.py
./db.sqlite3
./mysite/__init__.py
./mysite/settings.py
./mysite/urls.py
./mysite/wsgi.py
The one other change I made was adding a Meta subclass to my Entry class, so the first dozen lines look like this:
class Entry(models.Model):
user = models.ForeignKey(User)
pub_date = models.DateTimeField(default=now)
title = models.CharField(max_length=200)
slug = models.SlugField(null=True, blank=True)
body = models.TextField()
class Meta:
app_label = 'myapp'
# __unicode__() and save() as in the tutorial
If I don't do that, I get this in the console: RuntimeError: Model class myapp.models.Entry doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
Another thing I tried was python manage.py migrate. It found things to do, but this hasn't fixed this error.
Here's what I've got installed (in requirements.txt/virtualenv):
Django (1.10)
django-tastypie (0.13.3)
PyYAML (3.12)
mysqlclient (1.3.10) (although I haven't actually set it up yet—I'm using the default sqlite3 setup for now)
I'm running Python 3.4.3, but I got exactly the same error using a quite similar setup in Python 2.7.6.
Finally, here's the full stack trace from that HTTP 500 page:
{"error_message": "no such table: myapp_entry", "traceback": "Traceback (most recent call last):
File "~/myproject/virtualenv/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "~/myproject/virtualenv/lib/python3.4/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: myapp_entry
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "~/myproject/virtualenv/lib/python3.4/site-packages/tastypie/resources.py", line 219, in wrapper
response = callback(request, *args, **kwargs)
File "~/myproject/virtualenv/lib/python3.4/site-packages/tastypie/resources.py", line 450, in dispatch_list
return self.dispatch('list', request, **kwargs)
File "~/myproject/virtualenv/lib/python3.4/site-packages/tastypie/resources.py", line 482, in dispatch
response = method(request, **kwargs)
File "~/myproject/virtualenv/lib/python3.4/site-packages/tastypie/resources.py", line 1335, in get_list
to_be_serialized = paginator.page()
File "~/myproject/virtualenv/lib/python3.4/site-packages/tastypie/paginator.py", line 194, in page
count = self.get_count()
File "~/myproject/virtualenv/lib/python3.4/site-packages/tastypie/paginator.py", line 126, in get_count
return self.objects.count()
File "~/myproject/virtualenv/lib/python3.4/site-packages/django/db/models/query.py", line 369, in count
return self.query.get_count(using=self.db)
File "~/myproject/virtualenv/lib/python3.4/site-packages/django/db/models/sql/query.py", line 476, in get_count
number = obj.get_aggregation(using, ['__count'])['__count']
File "~/myproject/virtualenv/lib/python3.4/site-packages/django/db/models/sql/query.py", line 457, in get_aggregation
result = compiler.execute_sql(SINGLE)
File "~/myproject/virtualenv/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 835, in execute_sql
cursor.execute(sql, params)
File "~/myproject/virtualenv/lib/python3.4/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "~/myproject/virtualenv/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "~/myproject/virtualenv/lib/python3.4/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "~/myproject/virtualenv/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "~/myproject/virtualenv/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "~/myproject/virtualenv/lib/python3.4/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: myapp_entry
"}
Can anybody see what I'm doing wrong? Or does the tutorial not apply to these versions?

sqlite3.OperationalError: no such table: myapp_entry
For one, your project is using sqlite, not mysql. You should update your DATABASES setting.
Add myapp to your INSTALLED_APPS in your project settings.
Then, run ./manage.py migrate. After fixing INSTALLED_APPS Django should be able to find the app's Entry model and create the table for it.

Related

im not able to makemigrations to my already built model after extending user model to it in django

im just stuck with error while making migrations to my django project.
in my project which is already 50% dveloped i use owner model to represent owner of shop and then i used user model for login and for registration purpose.
so i tried to use user model in my owner model so i could utilise both model effectively with additional fields.
i tried to extend user model in owner model using onetoone field.
after doing that i was not able to do migrations so i deleted all migrations files but after that it was start giving this error while doing migrations:-
py manage.py makemigrations
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 "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\base.py", line 369, in execute
output = self.handle(*args, **options)
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 87, in handle
loader = MigrationLoader(None, ignore_no_migrations=True)
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__
self.build_graph()
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\loader.py", line 274, in build_graph
raise exc
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\loader.py", line 248, in build_graph
self.graph.validate_consistency()
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\graph.py", line 195, in validate_consistency
[n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)]
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\graph.py", line 195, in <listcomp>
[n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)]
File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\graph.py", line 58, in raise_error
raise NodeNotFoundError(self.error_message, self.key, origin=self.origin)
django.db.migrations.exceptions.NodeNotFoundError: Migration listings.0001_initial dependencies reference nonexistent parent node ('owners', '0001_initial')
here is my Owner Model :-
from django.db import models
from django.contrib.auth.models import User
class Owner(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE, default=False)
name=models.CharField(max_length=200)
photo=models.ImageField(upload_to='photos/%Y/%m/%d/')
description=models.TextField(blank=True)
phone=models.CharField(max_length=20)
email=models.CharField(max_length=20)
def __str__(self):
return self.name
im hoping that will get help on this because i'm totally stuck here and also not getting how to tackle this problem.
You are using the term "migration folder of my django project" (in a comment above), and that is wrong -- each app in your project has its own migration folder. Specifically, there is still a migration in your "listings" app, and it lists as a dependency one of the migrations you deleted.
after reviewing and debugging that stack trace i finally get rid of that problem.
i delete the migration file 0001 from my listing app which was having relationship with Owner Model and then when i run makemigrations command it didn't given me any error or exception like i mentioned above.

django.db.utils.OperationalError: (1054, "Unknown column

An interesting issue.
Getting Unknown column exception -- Please find the stack trace
I try to get new leads list and responded leads. I merge them. When I merge them there is an exception.
After debugging its found that new_leads method has exclude of two fields collection and delivery . If we make it one exclude all is well . I mean dont check the other, if we include both the filters we have an issue.
I tried using filter/ exclude etc. but it didnt work.
Query Set contains following method
def all_leads_related_to_user(self, user):
""" User new and past leads
Use this queryset for performing lead search.
"""
new_leads = self.new_leads_for_user(user)
responded_leads = self.leads_responded_by_user(user)
all_leads = (new_leads | responded_leads).distinct() <= Issue is here.
return all_leads
def new_leads_for_user(self, user):
....
# User's location filter
if user.sub_region_excluded_list:
sub_region_exclude_list = [10, 12]
qs = qs.exclude( Q(collection_point__sub_region_id__in=sub_region_exclude_list) |
Q(delivery_point__sub_region_id__in=sub_region_exclude_list))
# <== Make it just one exclude it works.
Model
class Suburb(models.Model):
state = models.ForeignKey(State, blank=False)
sub_region = models.ForeignKey(SubRegion, blank=False)
postcode = models.CharField(_('postcode'), blank=False, max_length=10)
name = models.CharField(_('suburb name'), blank=False, max_length=200)
class Load(models.Model):
.....
collection_point = models.ForeignKey(Suburb, related_name='collection_point', on_delete=models.SET_NULL, null=True)
delivery_point = models.ForeignKey(Suburb, related_name='delivery_point', on_delete=models.SET_NULL, null=True)
Stack Trace:-
>>> Load.objects.all_leads_related_to_user(User.objects.all()[0])
Load.objects.all_leads_related_to_user(User.objects.all()[0])
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/data/fq/venv/lib/python3.4/site-packages/django/db/models/query.py", line 226, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "/data/fq/venv/lib/python3.4/site-packages/django/db/models/query.py", line 250, in __iter__
self._fetch_all()
File "/data/fq/venv/lib/python3.4/site-packages/django/db/models/query.py", line 1103, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/data/fq/venv/lib/python3.4/site-packages/django/db/models/query.py", line 53, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch)
File "/data/fq/venv/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 886, in execute_sql
raise original_exception
File "/data/fq/venv/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 876, in execute_sql
cursor.execute(sql, params)
File "/data/fq/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 80, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/data/fq/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/data/fq/venv/lib/python3.4/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/data/fq/venv/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/data/fq/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/data/fq/venv/lib/python3.4/site-packages/django/db/backends/mysql/base.py", line 101, in execute
return self.cursor.execute(query, args)
File "/data/fq/venv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 250, in execute
self.errorhandler(self, exc, value)
File "/data/fq/venv/lib/python3.4/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler
raise errorvalue
File "/data/fq/venv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 247, in execute
res = self._query(query)
File "/data/fq/venv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 411, in _query
rowcount = self._do_query(q)
File "/data/fq/venv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 374, in _do_query
db.query(q)
File "/data/fq/venv/lib/python3.4/site-packages/MySQLdb/connections.py", line 292, in query
_mysql.connection.query(self, query)
django.db.utils.OperationalError: (1054, "Unknown column 'locations_suburb.sub_region_id' in 'having clause'")
>>>
I'm using MySqlDB
Note:-
All migrations are applied and Db is in right state
Update
Issue is related to MYSQL madating columns to be available in select statements when its creating a Having clause . Refer to -
Unknown column in 'having clause'.
Django in this instance is not adding as the column to be selected. hence the error.
I need to some how find a way to add this in the select clause with other params.
This usually pops up when you haven't made or applied migrations. Specifically, when you modify the fields any model in Django (or any ORM), you need to inform the SQL server so it can reflect it in its tables. Modern Django implements this by a series of migrations, so that if you have data from any time in the life of your project, you can run it on code from any time in history by simply running the migrations forwards or backwards.
Long story short, MySQL claims the sub_region field doesn't exist. You need to sync the tables to reflect your models.
There are two steps, making the migrations and running them on your server, shown below for your locations app. Take a backup before running the second command, especially on MySQL or SQLite!
$ python manage.py makemigrations locations
$ python manage.py migrate locations
This will cause the database server to create the column, and you should no longer get an OperationalError.
It is not a migration issue.
When having a HAVING Clause MYSQL mandates those parameters to be in selected, if not selected it will throw an exception.
Therefore I had to force Django to include both the fields by:
qs = qs.annotate(collection_point__sub_region_id = F("collection_point__sub_region_id"),
delivery_point__sub_region_id = F("delivery_point__sub_region_id"))
This is the answer to this issue:
Step 1. You need to fake the migrations
python manage.py migrate --fake
Step 2. Migrate again
python manage.py migrate
Step 3. Comment out the column for which the error comes up e.g. "Can't DROP 'address'
Step 4. Make migrations and migrate again
python manage.py makemigrations
python manage.py migrate
Since my table didn't have any data, I deleted it and recreated it on MySQL and then deleted it from Django. Finally I recreated on Django thus solving the error.

Django 1.4 tests not working on sqlite3

I am getting this error after upgrading to django 1.4 while running tests using sqlite:
Creating test database for alias 'default'...
Problem installing fixture '/home/devasia/pyserver/project/mysite/app/fixtures/test_data.json': Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/loaddata.py", line 196, in handle
obj.save(using=using)
File "/usr/local/lib/python2.7/dist-packages/django/core/serializers/base.py", line 165, in save
models.Model.save_base(self.object, using=using, raw=True)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 529, in save_base
rows = manager.using(using).filter(pk=pk_val)._update(values)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 557, in _update
return query.get_compiler(self.db).execute_sql(None)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 986, in execute_sql
cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 818, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
IntegrityError: Could not load auth.Permission(pk=31): columns content_type_id, codename are not unique
----------------------------------------------------------------------
Ran 1 test in 0.011s
OK
Destroying test database for alias 'default'...
This is my sample test case:
class CheckTest(TestCase):
fixtures = ['test_data.json']
def test_check(self):
c = Client()
c.login(username = 'test', password = 'test')
The fixtures are not that of old version. I have created this fixture using django 1.4 starting from 'syncdb' command. The tests are running well if I use postgresql as my test database(the tests run really slow).
Did I miss something while upgrading? I found this https://code.djangoproject.com/ticket/14731 but couldn't resolve the issue. (Please note that the only code/data from old project is the models)
Thanks

mysql exception when synchronizing db with django's manage.py script

I am relatively new to django. I have defined my db schema and validated it with no errors (manage.py validate reports 0 errors found).
Yet when I run ./manage.py syncdb
I get the following stack trace:
Creating table demo_foobar_one
Creating table demo_foobar_two
<snip>...</snip>
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 218, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 347, in handle
return self.handle_noargs(**options)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/commands/syncdb.py", line 103, in handle_noargs
emit_post_sync_signal(created_models, verbosity, interactive, db)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/sql.py", line 185, in emit_post_sync_signal
interactive=interactive, db=db)
File "/usr/local/lib/python2.6/dist-packages/django/dispatch/dispatcher.py", line 162, in send
response = receiver(signal=self, sender=sender, **named)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/auth/management/__init__.py", line 28, in create_permissions
defaults={'name': name, 'content_type': ctype})
File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 135, in get_or_create
return self.get_query_set().get_or_create(**kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 373, in get_or_create
obj.save(force_insert=True, using=self.db)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/base.py", line 435, in save
self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/base.py", line 528, in save_base
result = manager._insert(values, return_id=update_pk, using=using)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 195, in _insert
return insert_query(self.model, values, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 1479, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py", line 783, in execute_sql
cursor = super(SQLInsertCompiler, self).execute_sql(None)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py", line 727, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/util.py", line 15, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/mysql/base.py", line 86, in execute
return self.cursor.execute(query, args)
File "/usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3-py2.6-linux-i686.egg/MySQLdb/cursors.py", line 176, in execute
if not self._defer_warnings: self._warning_check()
File "/usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3-py2.6-linux-i686.egg/MySQLdb/cursors.py", line 92, in _warning_check
warn(w[-1], self.Warning, 3)
_mysql_exceptions.Warning: Data truncated for column 'name' at row 1
I have checked (and double checked) my table schema. All name field are CharField type with maximum length = 64. The backend db I am using is MySQL, so I am sure that indexes can be created for strings of length 64.
What could be causing this error (I suspect it is a misleading error message - even though its coming from the db itself)...
The traceback is happening during the creation of a django.contrib.auth.Permission: some of these get created for your models automatically as part of syncdb.
Permission.name has max_length=50, so you probably have an application and/or model class with a really long name?
Try the following query in manage.py dbshell:
SELECT * FROM auth_permission WHERE LENGTH(name) = 50;
If you cannot change your model name, then you can fix this problem by reducing the length of the generated Permission.name by specifying verbose_name in the model Meta class (see here for more details):
class MyVeryLongModelNameThatIsBreakingMyMigration(models.Model):
class Meta:
verbose_name = 'my long model'
Update
There's an open (as of 2013) Django ticket to fix this:
#8162 (Increase Permission.name max_length)
As Piet Delport noted, the problem is that your model name is too long.
You're certainly going to have to shorten your model name, and then clean up your database. How you do that depends upon where you are in the development process.
If this is a brand new application, with a dedicated database, and no actual data, the simple answer is to drop and recreate the database, and then re-run python manage.py syncdb.
If you have other tables in the database that need to be left alone, but the tables for your Django have no 'real' data, and can thus be dropped without damage, then you can use manage.py sqlclear to generate SQL DDL to drop all of the Django-generated tables, constraints, and indexes.
Do the following:
apps="auth contenttypes sessions sites messages admin <myapp1> <myapp2>"
python manage.py sqlclear ${apps} > clear.sql
You can feed the generated script to mysql or python manage.py dbshell. Once that's done, you can re-run python manage.py syncdb.
If you have actual data in your database tables that can't be dropped or deleted: Slap yourself and repeat 100 times "I will never do development against a production database again. I will always back up my databases before changing them." Now you're going to have to hand-code SQL to change the affected table name, as well as anything else that references it and any references in the auth_permissions table and any other Django system tables. Your actual steps will depend entirely upon the state of your database and tables.
I also got error like this one using postgresql django 1.2, but the problem was not the length, but using ugettext_lazy for translating the names. ('can_purge', _("Can purge")) is evidently unacceptable, since the name is stored in the database as text

How to create admin user in django tests.py

I'm trying to create an admin user as part of my tests.py to check on persmissions.
UPDATE:
The tests.py is standard format that subclasses TestCase and the code below is called in the setUp() function.
I can create a normal user but not an admin user. If I try this:
self.adminuser = User.objects.create_user('admin', 'admin#test.com', 'pass')
self.adminuser.save()
self.adminuser.is_staff = True
self.adminuser.save()
OR
self.adminuser = User.objects.create_superuser('admin', 'admin#test.com', 'pass')
self.adminuser.save()
I get:
Warning: Data truncated for column 'name' at row 1
If I remove the is_staff line all is well (except I can't do my test!)
Do I have to load admin users as fixtures?
UserProfile is defined as follows:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
organisation = models.ForeignKey(Organisation, null=True, blank=True)
telephone = models.CharField(max_length=20, null=True, blank=True)
and full error traceback is:
Traceback (most recent call last):
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/test/testcases.py", line 242, in __call__
self._pre_setup()
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/test/testcases.py", line 217, in _pre_setup
self._fixture_setup()
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/test/testcases.py", line 440, in _fixture_setup
return super(TestCase, self)._fixture_setup()
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/test/testcases.py", line 222, in _fixture_setup
call_command('flush', verbosity=0, interactive=False)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/core/management/__init__.py", line 166, in call_command
return klass.execute(*args, **defaults)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/core/management/base.py", line 222, in execute
output = self.handle(*args, **options)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/core/management/base.py", line 351, in handle
return self.handle_noargs(**options)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/core/management/commands/flush.py", line 61, in handle_noargs
emit_post_sync_signal(models.get_models(), verbosity, interactive)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/core/management/sql.py", line 205, in emit_post_sync_signal
interactive=interactive)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/dispatch/dispatcher.py", line 166, in send
response = receiver(signal=self, sender=sender, **named)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/contrib/auth/management/__init__.py", line 28, in create_permissions
defaults={'name': name, 'content_type': ctype})
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/manager.py", line 123, in get_or_create
return self.get_query_set().get_or_create(**kwargs)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/query.py", line 335, in get_or_create
obj.save(force_insert=True)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/base.py", line 410, in save
self.save_base(force_insert=force_insert, force_update=force_update)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/base.py", line 495, in save_base
result = manager._insert(values, return_id=update_pk)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/manager.py", line 177, in _insert
return insert_query(self.model, values, **kwargs)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/query.py", line 1087, in insert_query
return query.execute_sql(return_id)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/sql/subqueries.py", line 320, in execute_sql
cursor = super(InsertQuery, self).execute_sql(None)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/sql/query.py", line 2369, in execute_sql
cursor.execute(sql, params)
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/backends/mysql/base.py", line 84, in execute
return self.cursor.execute(query, args)
File "build/bdist.linux-x86_64/egg/MySQLdb/cursors.py", line 175, in execute
File "build/bdist.linux-x86_64/egg/MySQLdb/cursors.py", line 89, in _warning_check
File "/usr/lib64/python2.4/warnings.py", line 61, in warn
warn_explicit(message, category, filename, lineno, module, registry)
File "/usr/lib64/python2.4/warnings.py", line 96, in warn_explicit
raise message
Warning: Data truncated for column 'name' at row 1
The answer seems to be that you can't create an admin user in setUp but you can in any other function so if you want an admin user in testing, use a fixture!
I'd use the built-in create_superuser and log the user in before making any requests. The following should work:
from django.contrib.auth.models import User
from django.test.client import Client
# store the password to login later
password = 'mypassword'
my_admin = User.objects.create_superuser('myuser', 'myemail#test.com', password)
c = Client()
# You'll need to log him in before you can send requests through the client
c.login(username=my_admin.username, password=password)
# tests go here
Update 2
Executed the snippet to create the superuser from within a test case (subclass of django.test.TestCase). Everything went fine. Also created and saved an instance of UserProfile with user = self.adminuser. That too worked.
Update
This line is interesting:
File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/contrib/auth/management/__init__.py", line 28, in create_permissions
defaults={'name': name, 'content_type': ctype})
Looks like execution fails when creating permissions.
Original Answer
Warning: Data truncated for column 'name' at row 1
Strange. I tried this from the Django shell and it worked for me. I am using Postgresql 8.3 and Django 1.2.1 on Ubuntu Jaunty. Can you give more details about which version of Django/database are you using?
Also User does not have a name attribute. Can you double check if you are using auth.User?
Do I have to load admin users as fixtures?
You don't have to. But if you are creating this admin user solely for testing purposes then it would be a good idea to add a Fixture. That is what I do in my projects.