IntegrityError when creating a brand new model instance

55 views
Skip to first unread message

Some Developer

unread,
Feb 8, 2013, 2:18:29 AM2/8/13
to django...@googlegroups.com
I have a model for a Tag object with simply has two fields. A title
(which has the unique constraint) and a description. I also have a
FormView based view class which handles the creation of Tag objects.

When I try and save the object in the form_valid() method I always get
an IntegrityError stating that the title column is not unique. This is
somewhat puzzling as I have deleted the SQLite database file and
recreated it using syncdb / migrate so it is completely empty.

I'm completely baffled by this error.

Andre Terra

unread,
Feb 8, 2013, 9:08:18 AM2/8/13
to django...@googlegroups.com
Please post traceback, settings.py, etc.



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.



Some Developer

unread,
Feb 9, 2013, 2:50:38 AM2/9/13
to django...@googlegroups.com
On 08/02/13 14:08, Andre Terra wrote:
> Please post traceback, settings.py, etc.
>
> On Fri, Feb 8, 2013 at 5:18 AM, Some Developer
> <someukd...@gmail.com <mailto:someukd...@gmail.com>> wrote:
>
> I have a model for a Tag object with simply has two fields. A title
> (which has the unique constraint) and a description. I also have a
> FormView based view class which handles the creation of Tag objects.
>
> When I try and save the object in the form_valid() method I always
> get an IntegrityError stating that the title column is not unique.
> This is somewhat puzzling as I have deleted the SQLite database file
> and recreated it using syncdb / migrate so it is completely empty.
>
> I'm completely baffled by this error.

I've been using Django for years and have never had this problem before.
Hopefully someone will be able to shed some light on it as it is rather
annoying.

The only thing I am doing now that I haven't done in the past is using
class based views.

Settings:

The settings are just the default pretty much. The database section is
below though.

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(DIRNAME, 'data/data.db'),
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}

Traceback:

Environment:


Request Method: POST
Request URL: http://localhost:8000/blog/tag/create/

Django Version: 1.4.3
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'debug_toolbar',
'debug_toolbar_htmltidy',
'inspector_panel',
'debug_toolbar_user_panel',
'compressor',
'registration',
'djcelery',
'south',
'blog',
'controlpanel',
'docs',
'legal',
'support',
'bugs',
'general')
Installed Middleware:
('django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.gzip.GZipMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.transaction.TransactionMiddleware')


Traceback:
File
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/core/handlers/base.py"
in get_response
111. response = callback(request,
*callback_args, **callback_kwargs)
File
"/home/somedeveloper/Documents/Development/Python/djangostormcloud/djangostormcloud/decorators/superuser.py"
in decorator
17. return f(request, *args, **kwargs)
File
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/views/generic/base.py"
in view
48. return self.dispatch(request, *args, **kwargs)
File
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/views/generic/base.py"
in dispatch
69. return handler(request, *args, **kwargs)
File
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/views/generic/edit.py"
in post
138. return self.form_valid(form)
File
"/home/somedeveloper/Documents/Development/Python/djangostormcloud/blog/views.py"
in form_valid
134. tag.save()
File
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/db/models/base.py"
in save
463. self.save_base(using=using, force_insert=force_insert,
force_update=force_update)
File
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/db/models/base.py"
in save_base
551. result = manager._insert([self], fields=fields,
return_id=update_pk, using=using, raw=raw)
File
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/db/models/manager.py"
in _insert
203. return insert_query(self.model, objs, fields, **kwargs)
File
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/db/models/query.py"
in insert_query
1593. return query.get_compiler(using=using).execute_sql(return_id)
File
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/db/models/sql/compiler.py"
in execute_sql
912. cursor.execute(sql, params)
File
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/db/backends/util.py"
in execute
40. return self.cursor.execute(sql, params)
File
"/home/somedeveloper/Documents/Development/PythonEnvironments/dsc-env/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py"
in execute
344. return Database.Cursor.execute(self, query, params)

Exception Type: IntegrityError at /blog/tag/create/
Exception Value: column title is not unique

Some Developer

unread,
Feb 9, 2013, 3:44:19 AM2/9/13
to django...@googlegroups.com
On 08/02/13 14:08, Andre Terra wrote:
> Please post traceback, settings.py, etc.
>
> On Fri, Feb 8, 2013 at 5:18 AM, Some Developer
> <someukd...@gmail.com <mailto:someukd...@gmail.com>> wrote:
>
> I have a model for a Tag object with simply has two fields. A title
> (which has the unique constraint) and a description. I also have a
> FormView based view class which handles the creation of Tag objects.
>
> When I try and save the object in the form_valid() method I always
> get an IntegrityError stating that the title column is not unique.
> This is somewhat puzzling as I have deleted the SQLite database file
> and recreated it using syncdb / migrate so it is completely empty.
>
> I'm completely baffled by this error.

Opps. I forgot to post the code.

class TagCreate(FormView):
template_name = 'blog/tag_create.html'
success_url = reverse_lazy('blog_tag_create_confirmed')
model = BlogTag
form_class = CreateTagForm

def form_valid(self, form):
tag = BlogTag(
title=form.cleaned_data['title'],
description=form.cleaned_data['description'],
num_articles=0)

tag.save()

return super(TagCreate, self).form_valid(form)

Bill Freeman

unread,
Feb 10, 2013, 10:07:42 AM2/10/13
to django...@googlegroups.com
Did you previously have a field named 'title' in this model that was marked unique, that you have since removed?  If so, the column may still be in the database with a unique constraint.  Since it's no longer in the model, some default may be being used when you save, and that's obviously not unique.  Use suitable tools for your database (if PostgreSQL, I suggest PGAdminIII) to examine the schema.  You may be able to drop the column, or at least the constraint (back up the database first).

If there never was such a field, then the problem originates in another model.  You still may be able to figure it out by inspecting the database schema.  You can also temporarily set up to catch the Integrity Error close to the origin, and call pdb.set_trace(), where you can examine the query to see what models are involved.

Bill

Some Developer

unread,
Feb 10, 2013, 10:50:39 AM2/10/13
to django...@googlegroups.com
On 10/02/13 15:07, Bill Freeman wrote:
> Did you previously have a field named 'title' in this model that was
> marked unique, that you have since removed? If so, the column may still
> be in the database with a unique constraint. Since it's no longer in
> the model, some default may be being used when you save, and that's
> obviously not unique. Use suitable tools for your database (if
> PostgreSQL, I suggest PGAdminIII) to examine the schema. You may be
> able to drop the column, or at least the constraint (back up the
> database first).
>
> If there never was such a field, then the problem originates in another
> model. You still may be able to figure it out by inspecting the
> database schema. You can also temporarily set up to catch the Integrity
> Error close to the origin, and call pdb.set_trace(), where you can
> examine the query to see what models are involved.
>
> Bill

OK, I've just found something rather strange. If I just do a simple:

tag = BlogTag(title=form.cleaned_data['title'],
description=form.cleaned_data['description'],
num_articles=0)

tag.save()

I get an IntegrityError and the model fails to save. On the other hand
if I do the following:

try:
tag = BlogTag(title=form.cleaned_data['title'],
description=form.cleaned_data['description'],
num_articles=0)

tag.save()

except Exception:
pass

the model saves correctly (I've checked manually in the SQLite database)
and there is no error shown at all (as expected since I have ignored the
exception).

Any idea why this is the case? If it truly were a database constraint
violation I would have assumed that it would fail to save no matter what
you did regarding Python exceptions.

This feels like a bug in Django to me.

Suggestions welcome.

Bill Freeman

unread,
Feb 11, 2013, 9:54:34 AM2/11/13
to django...@googlegroups.com

I have to agree that catching exceptions doesn't clear IntegrityError.  But that still doesn't tell us where the bug is.

Does this happen on the development server?  If so, then my suggestion is to sprinkle in a pdb.set_trace() or two, poke around and/or single step over a few things, then go around again and single step into the thing that fails, and repeat until enlightened.

If it only happens on a production server, you're stuck with printing stuff.  For instance, since your except only has a pass, we don't actually know whether it was reached.  You can't in general, print to stdout.  I believe that apache/mod_wsgi puts stuff sent to stderr in the apacvhe longs.  Django's logging may  help.  I'm fond of writing a little function that appends its text argument to a file of your choice.

Bill

Some Developer

unread,
Feb 16, 2013, 2:46:42 PM2/16/13
to django...@googlegroups.com
On 11/02/13 14:54, Bill Freeman wrote:
>
>
> On Sun, Feb 10, 2013 at 10:50 AM, Some Developer
> <someukd...@gmail.com <mailto:someukd...@gmail.com>> wrote:
>
> On 10/02/13 15:07, Bill Freeman wrote:
>
> Did you previously have a field named 'title' in this model that was
> marked unique, that you have since removed? If so, the column
> may still
> be in the database with a unique constraint. Since it's no
> longer in
> the model, some default may be being used when you save, and that's
> obviously not unique. Use suitable tools for your database (if
> PostgreSQL, I suggest PGAdminIII) to examine the schema. You may be
> able to drop the column, or at least the constraint (back up the
> database first).
>
> If there never was such a field, then the problem originates in
> another
> model. You still may be able to figure it out by inspecting the
> database schema. You can also temporarily set up to catch the
> Integrity
> Error close to the origin, and call pdb.set_trace(), where you can
> examine the query to see what models are involved.
>
> Bill
>
>
> OK, I've just found something rather strange. If I just do a simple:
>
> tag = BlogTag(title=form.cleaned___data['title'],
>
> description=form.cleaned_data[__'description'],
> num_articles=0)
>
> tag.save()
>
> I get an IntegrityError and the model fails to save. On the other
> hand if I do the following:
>
> try:
> tag = BlogTag(title=form.cleaned___data['title'],
>
> description=form.cleaned_data[__'description'],
Apologies for the late response I've had a somewhat busy week with work.

Problem solved. It was a bug in Django Debug Toolbar. Disabling the
following panel fixed the issue completely.

'debug_toolbar.panels.profiling.ProfilingDebugPanel',

I'm glad that particular problem is sorted :).
Reply all
Reply to author
Forward
0 new messages