Just starting with Django and have began creating an application for test purposes. However, when I specify rollercoasters to ManyToMany and add an instance of a Park via the admin UI I get an:
IntreityError, rollercoasters_id may not be NULL
I have just completed a book on this and the code is more or less exact as the books (the code works in the book).
What am I doing wrong?
The application works when I have ForeignKey instead of ManyToMany
from django.db import models
class Company(models.Model):
name=models.CharField(max_length=30)
location=models.CharField(max_length=30)
website=models.URLField()
def __unicode__(self):
return self.name
class Constructor(models.Model):
name=models.CharField(max_length=30)
location=models.CharField(max_length=30)
contactnumber=models.CharField(max_length=30)
website=models.URLField()
def __unicode__(self):
return self.name
class RollerCoasters(models.Model):
name=models.CharField(max_length=30)
dateopenned=models.DateField
type=models.CharField(max_length=30)
builtby=models.ForeignKey(Constructor)
dateopenned=models.DateField()
def __unicode__(self):
return self.name
class Parks (models.Model):
name=models.CharField(max_length=30)
parent=models.ForeignKey(Company)
location=models.CharField(max_length=1000)
rollercoasters=models.ManyToManyField(RollerCoasters)
dateopenned=models.DateField()
def __unicode__(self):
return self.name
Error:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/Parks/parks/add/
Django Version: 1.4.2
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',
'Parks',
'django.contrib.admin',
'django.contrib.admindocs')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in wrapper
366. return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
89. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in inner
196. return view(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapper
25. return bound_func(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in bound_func
21. return func(self, *args2, **kwargs2)
File "C:\Python27\lib\site-packages\django\db\transaction.py" in inner
209. return func(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in add_view
955. self.save_model(request, new_object, form, False)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in save_model
709. obj.save()
File "C:\Python27\lib\site-packages\django\db\models\base.py" in save
463. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "C:\Python27\lib\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 "C:\Python27\lib\site-packages\django\db\models\manager.py" in _insert
203. return insert_query(self.model, objs, fields, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in insert_query
1593. return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
910. cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\util.py" in execute
40. return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
344. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /admin/Parks/parks/add/
Exception Value: Parks_parks.rollercoasters_id may not be NULL
You can't just swap between a foreign key and many to many field. If you have a foreign key, Django creates a database column e.g. rollercoaster_id. If you use a many to many, Django creates an intermediary join table.
To switch from a foreign key to a many to many field, you must do one of the following:
drop the tables and then run syncdb so that Django recreates them. You will lose any data.
manually update the database schema yourself, using the output of the manage.py sql command as a guide
use the schema migration tool South.
Related
I have a Django model that uploads photos to a user's account. The upload model uses a Django auth user as a foreign key. I needed to ensure that each user could only upload 20 photos total and I wanted to do this at the model level so even the admin could not upload more. I got that working in a way but it broke my admin form validation. If I choose a related user, everything goes perfectly. It stops me from uploading more than 20 photos. But if I don't choose a user it gives me RelatedObjectDoesNotExist error. I am including my code and traceback here. Help would be appreciated.
My models.py
def photo_count(self):
theModel = self.__class__
refModel = theModel.objects.filter(user=self.user)
picCount = refModel.count()
if picCount ==20:
print(picCount)
raise ValidationError ("You have already uploaded 20 photos. Delete some to upload more.")
class StarPhotos(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
PHOTO_CATEGORY = (
('HS', "Head Shot"),
('WP', "Western Party Wear"),
('IP', "Indian Party Wear"),
('SW', "Swim Wear"),
('CW', "Casual Wear"),
)
category = models.CharField(max_length=2, choices=PHOTO_CATEGORY, default='CW')
# This FileField should preferaby be changed to ImageField with pillow installed.
photos = models.FileField(max_length=200, upload_to='images/',)
def __str__(self):
return "Images for {0}".format(self.user)
def clean(self):
photo_count(self)
class Meta:
verbose_name_plural = "Star Photos"
Traceback
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/castar/starphotos/add/
Django Version: 1.11.1
Python Version: 3.6.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'castar.apps.CastarConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "D:\websites\powah\lib\site-packages\django\core\handlers\exception.py" in inner
41. response = get_response(request)
File "D:\websites\powah\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "D:\websites\powah\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\websites\powah\lib\site-packages\django\contrib\admin\options.py" in wrapper
551. return self.admin_site.admin_view(view)(*args, **kwargs)
File "D:\websites\powah\lib\site-packages\django\utils\decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "D:\websites\powah\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "D:\websites\powah\lib\site-packages\django\contrib\admin\sites.py" in inner
224. return view(request, *args, **kwargs)
File "D:\websites\powah\lib\site-packages\django\contrib\admin\options.py" in add_view
1508. return self.changeform_view(request, None, form_url, extra_context)
File "D:\websites\powah\lib\site-packages\django\utils\decorators.py" in _wrapper
67. return bound_func(*args, **kwargs)
File "D:\websites\powah\lib\site-packages\django\utils\decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "D:\websites\powah\lib\site-packages\django\utils\decorators.py" in bound_func
63. return func.__get__(self, type(self))(*args2, **kwargs2)
File "D:\websites\powah\lib\site-packages\django\contrib\admin\options.py" in changeform_view
1408. return self._changeform_view(request, object_id, form_url, extra_context)
File "D:\websites\powah\lib\site-packages\django\contrib\admin\options.py" in _changeform_view
1440. if form.is_valid():
File "D:\websites\powah\lib\site-packages\django\forms\forms.py" in is_valid
183. return self.is_bound and not self.errors
File "D:\websites\powah\lib\site-packages\django\forms\forms.py" in errors
175. self.full_clean()
File "D:\websites\powah\lib\site-packages\django\forms\forms.py" in full_clean
386. self._post_clean()
File "D:\websites\powah\lib\site-packages\django\forms\models.py" in _post_clean
396. self.instance.full_clean(exclude=exclude, validate_unique=False)
File "D:\websites\powah\lib\site-packages\django\db\models\base.py" in full_clean
1233. self.clean()
File "D:\websites\powah\src\castar\models.py" in clean
75. photo_count(self)
File "D:\websites\powah\src\castar\models.py" in photo_count
49. refModel = theModel.objects.filter(user=self.user)
File "D:\websites\powah\lib\site-packages\django\db\models\fields\related_descriptors.py" in __get__
194. "%s has no %s." % (self.field.model.__name__, self.field.name)
Exception Type: RelatedObjectDoesNotExist at /admin/castar/starphotos/add/
Exception Value: StarPhotos has no user.
I'm having some troubles while using a custom user model and the admin
# models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class Employee(AbstractUser):
class Meta:
verbose_name = 'Employee'
verbose_name_plural = 'Employees'
# settings.py
AUTH_USER_MODEL = 'myapp.Employee'
# admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from myapp.models import Employee
admin.site.register(Employee, UserAdmin)
Well when I try to add a new user, it trows me this error:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8050/admin/chaos/employee/add/
Django Version: 1.7.1
Python Version: 2.7.6
Installed Applications:
['admin_tools',
'admin_tools.theming',
'admin_tools.menu',
'admin_tools.dashboard',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions',
'reversion',
'mptt',
'imperavi',
'django_mptt_admin',
'document',
'chaos']
Installed Middleware:
['django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
584. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
204. return view(request, *args, **kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
29. return bound_func(*args, **kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
76. return view(request, *args, **kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
25. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
29. return bound_func(*args, **kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
25. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/transaction.py" in inner
394. return func(*args, **kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/contrib/auth/admin.py" in add_view
121. extra_context)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in add_view
1454. return self.changeform_view(request, None, form_url, extra_context)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
29. return bound_func(*args, **kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
25. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/transaction.py" in inner
394. return func(*args, **kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in changeform_view
1397. if form.is_valid():
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/forms/forms.py" in is_valid
162. return self.is_bound and not bool(self.errors)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/forms/forms.py" in errors
154. self.full_clean()
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/forms/forms.py" in full_clean
353. self._clean_fields()
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/forms/forms.py" in _clean_fields
371. value = getattr(self, 'clean_%s' % name)()
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/contrib/auth/forms.py" in clean_username
101. User._default_manager.get(username=username)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
92. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/query.py" in get
351. num = len(clone)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/query.py" in __len__
122. self._fetch_all()
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/query.py" in _fetch_all
966. self._result_cache = list(self.iterator())
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/query.py" in iterator
265. for row in compiler.results_iter():
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in results_iter
700. for rows in self.execute_sql(MULTI):
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
786. cursor.execute(sql, params)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
81. return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
65. return self.cursor.execute(sql, params)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/utils.py" in __exit__
94. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
65. return self.cursor.execute(sql, params)
Exception Type: ProgrammingError at /admin/chaos/employee/add/
Exception Value: relation "auth_user" does not exist
LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user...
Anybody experienced the same thing and any hint to solve it?
I had a suspect that I need also to subclass the UserCreationForm and UserChangeForm used by the original UserAdmin, but if it is the correct way, I honestly don't see the advantages of using a custom user model rather that create a one-to-one model (e.g. Profile) to extend the original User.
Thanks
Luca
Good day, Luke!
Please, look at django docs: https://docs.djangoproject.com/en/dev/topics/auth/customizing/
Just check, what model you are using: CustomUser or AbstractBaseUser.
As I can see, now it's AbstractUser.
I am just starting out to develop a Django Blog, and am following this youtube tutorial - https://www.youtube.com/watch?v=7rgph8en0Jc&spfreload=1
I am using Django 1.6.6.
Everytime I try to add Entry in Admin, I get this error. Thanks for your help!
Environment:
Django Version: 1.6.6
Python Version: 2.7.8
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'niceblog',
'django_markdown')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\core\handlers\base.py"
in get_response
112. response = wrapped_callback(request, *callback_args, >**callback_kwargs)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\contrib\admin\options.py"
in wrapper
450. return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\utils\decorators.py"
in _wrapped_view
99. response = view_func(request, *args, **kwargs)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\views\decorators\cache.py"
in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\contrib\admin\sites.py"
in inner
198. return view(request, *args, **kwargs)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\utils\decorators.py"
in _wrapper
29. return bound_func(*args, **kwargs)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\utils\decorators.py"
in _wrapped_view
99. response = view_func(request, *args, **kwargs)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\utils\decorators.py"
in bound_func
25. return func(self, *args2, **kwargs2)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\db\transaction.py"
in inner
371. return func(*args, **kwargs)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\contrib\admin\options.py"
in add_view
1149. self.save_model(request, new_object, form, False)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\contrib\admin\options.py"
in save_model
878. obj.save()
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\db\models\base.py"
in save
545. force_update=force_update, update_fields=update_fields)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\db\models\base.py"
in save_base
573. updated = self._save_table(raw, cls, force_insert, force_update, using, >update_fields)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\db\models\base.py"
in _save_table
654. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\db\models\base.py"
in _do_insert
687. using=using, raw=raw)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\db\models\manager.py"
in _insert
232. return insert_query(self.model, objs, fields, **kwargs)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\db\models\query.py"
in insert_query
1514. return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\db\models\sql\compiler.py"
in execute_sql
903. cursor.execute(sql, params)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\db\backends\util.py"
in execute
69. return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\db\backends\util.py"
in execute
53. return self.cursor.execute(sql, params)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\db\utils.py"
in exit
99. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\db\backends\util.py"
in execute
53. return self.cursor.execute(sql, params)
File "C:\Users\user\desktop\firstblog\lib\site-packages\django\db\backends\sqlite3\base.py"
in execute
452. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /admin/niceblog/entry/add/
Exception Value: niceblog_entry.slug may not be NULL
Everytime I try to edit Entry in Admin, it throws this error
Environment:
Django Version: 1.6.6 Python Version: 2.7.8 Installed Applications:
('django.contrib.admin', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.staticfiles', 'niceblog',
'django_markdown') Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback: File
"C:\Users\user\desktop\firstblog\lib\site-packages\django\core\handlers\base.py"
in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user\desktop\firstblog\lib\site-packages\django\contrib\admin\options.py"
in wrapper
450. return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\user\desktop\firstblog\lib\site-packages\django\utils\decorators.py"
in _wrapped_view
99. response = view_func(request, *args, **kwargs) File "C:\Users\user\desktop\firstblog\lib\site-packages\django\views\decorators\cache.py"
in _wrapped_view_func
52. response = view_func(request, *args, **kwargs) File "C:\Users\user\desktop\firstblog\lib\site-packages\django\contrib\admin\sites.py"
in inner
198. return view(request, *args, **kwargs) File "C:\Users\user\desktop\firstblog\lib\site-packages\django\utils\decorators.py"
in _wrapper
29. return bound_func(*args, **kwargs) File "C:\Users\user\desktop\firstblog\lib\site-packages\django\utils\decorators.py"
in _wrapped_view
99. response = view_func(request, *args, **kwargs) File "C:\Users\user\desktop\firstblog\lib\site-packages\django\utils\decorators.py"
in bound_func
25. return func(self, *args2, **kwargs2) File "C:\Users\user\desktop\firstblog\lib\site-packages\django\db\transaction.py"
in inner
371. return func(*args, **kwargs) File "C:\Users\user\desktop\firstblog\lib\site-packages\django\contrib\admin\options.py"
in change_view
1255. form = ModelForm(instance=obj) File "C:\Users\user\desktop\firstblog\lib\site-packages\django\forms\models.py"
in init
315. object_data = model_to_dict(instance, opts.fields, opts.exclude) File
"C:\Users\user\desktop\firstblog\lib\site-packages\django\forms\models.py"
in model_to_dict
141. data[f.name] = list(f.value_from_object(instance).values_list('pk', flat=True)) File
"C:\Users\user\desktop\firstblog\lib\site-packages\django\db\models\query.py"
in iter
96. self._fetch_all() File "C:\Users\user\desktop\firstblog\lib\site-packages\django\db\models\query.py"
in _fetch_all
857. self._result_cache = list(self.iterator()) File "C:\Users\user\desktop\firstblog\lib\site-packages\django\db\models\query.py"
in iterator
1068. for row in self.query.get_compiler(self.db).results_iter(): File
"C:\Users\user\desktop\firstblog\lib\site-packages\django\db\models\sql\compiler.py"
in results_iter
713. for rows in self.execute_sql(MULTI): File "C:\Users\user\desktop\firstblog\lib\site-packages\django\db\models\sql\compiler.py"
in execute_sql
786. cursor.execute(sql, params) File "C:\Users\user\desktop\firstblog\lib\site-packages\django\db\backends\util.py"
in execute
69. return super(CursorDebugWrapper, self).execute(sql, params) File
"C:\Users\user\desktop\firstblog\lib\site-packages\django\db\backends\util.py"
in execute
53. return self.cursor.execute(sql, params) File "C:\Users\user\desktop\firstblog\lib\site-packages\django\db\utils.py"
in exit
99. six.reraise(dj_exc_type, dj_exc_value, traceback) File
"C:\Users\user\desktop\firstblog\lib\site-packages\django\db\backends\util.py"
in execute
53. return self.cursor.execute(sql, params) File "C:\Users\user\desktop\firstblog\lib\site-packages\django\db\backends\sqlite3\base.py"
in execute
452. return Database.Cursor.execute(self, query, params)
Exception Type: OperationalError at /admin/niceblog/entry/2/ Exception
Value: no such table: niceblog_entry_tags
models.py file --->
class Tag(models.Model):
slug = models.SlugField(max_length=200, unique=True)
def __unicode__(self):
return self.slug
class Entry(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
publish = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField(Tag)
def __unicode__(self):
return self.title
class Meta:
verbose_name = "Blog Entry"
verbose_name_plural = "Blog Entries"
ordering = ['-created']
admin.py file --->
class EntryAdmin(MarkdownModelAdmin):
list_display = ("title", "created")
admin.site.register(Entry, EntryAdmin)
admin.site.register(Tag)
I guess, Entry.tags was added after table creation.
If it's possible to upgrade django to 1.7 then you can use built-in migrations.
Firstable reset your app to actual db schema, i.e. remove tags field, then:
# Create initial migrations
$ python manage.py makemigrations your_app
# Migrate
$ python manage.py migrate your_app
# Add your tags field. Repeat
$ python manage.py makemigrations your_app
$ python manage.py migrate your_app
If you want to stay on django 1.6, use South. It's pretty much the same:
# Create initial migrations
$ python manage.py schemamigration your_app intial --init
# Migrate
$ python manage.py migrate your_app --fake
# Add your tags field. Create migration
$ python manage.py schemamigration your_app add_tags --auto
$ python manage.py migrate your_app
I'm using Django 1.4.1 with postgresql 9.1.
I need to add a profile to the User given with the auth app, and to allow the admin app to create and edit this profile.
Thus I've been following the docs section Storing additional information about users :
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User)
bio = models.TextField(null = True, blank = True)
contact = models.TextField(null = True, blank = True)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
settings.py
...
AUTH_PROFILE_MODULE = 'userprofile.UserProfile'
...
I also activated the django.contrib.auth and django.contrib.admin apps in INSTALLED_APPS.
admin.py
class UserProfileInline(admin.StackedInline):
model = UserProfile
can_delete = False
verbose_name_plural = 'profile'
class UserAdmin(UserAdmin):
inlines = (UserProfileInline, )
# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
Problem
Now, when I run the admin app and ask to add (create) a new user, I'm asked to create my user through a two-step process : first, a page asking for only the username, password (twice), and my two UserProfile fields.
If I type only the username and the password (twice) and click "Save", I'm showed the second page of the process, which allows to fill in all the other User fields, as well as my UserProfile fields. There's a message saying "The user "xxxxx" was added successfully. You may edit it again below.", and fortunately I can edit fields from both models, it works.
But if I try to type anything into one or both of my UserProfile fields in the first page, the submit fails with the message :
IntegrityError at /admin/auth/user/add/
duplicate key value violates unique constraint "userprofile_userprofile_user_id_key"
DETAIL: Key (user_id)=(7) already exists.
The "7" is incremented each time I try.
How can that behavior be avoided, or alternatively how can I prevent the profile fields to be editable in the first page, but letting them be edited in the second page ?
Full traceback :
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/auth/user/add/
Django Version: 1.4.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'userprofile')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in wrapper
366. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
89. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in inner
196. return view(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
69. return view(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper
25. return bound_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func
21. return func(self, *args2, **kwargs2)
File "/usr/local/lib/python2.7/dist-packages/django/db/transaction.py" in inner
209. return func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/admin.py" in add_view
114. extra_context)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper
25. return bound_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func
21. return func(self, *args2, **kwargs2)
File "/usr/local/lib/python2.7/dist-packages/django/db/transaction.py" in inner
209. return func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in add_view
956. self.save_related(request, form, formsets, False)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in save_related
733. self.save_formset(request, form, formset, change=change)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in save_formset
721. formset.save()
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in save
497. return self.save_existing_objects(commit) + self.save_new_objects(commit)
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in save_new_objects
628. self.new_objects.append(self.save_new(form, commit=commit))
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in save_new
731. obj.save()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save
463. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/usr/local/lib/python2.7/dist-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 "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in _insert
203. return insert_query(self.model, objs, fields, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in insert_query
1576. return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py" in execute_sql
910. cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py" in execute
40. return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/postgresql_psycopg2/base.py" in execute
52. return self.cursor.execute(query, args)
Exception Type: IntegrityError at /admin/auth/user/add/
Exception Value: duplicate key value violates unique constraint "userprofile_userprofile_user_id_key"
DETAIL: Key (user_id)=(7) already exists.`
As CadentOrange mentioned in a comment, the solution to this problem is described in this answer.
The problem is with using an inline admin form. Here's what happens:
It saves the main model (User)
Due to (1), The post_save signal handler for User is fired, which creates a new UserProfile object
Each inline model is saved (including another copy of your UserProfile, resulting in the dupe).
instead of
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
do a
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.get_or_create(user=instance)
You are creating new user profile object even for edit.
The create_user_profile signal and the admin form try to create the same UserProfile. You can override LocalUserAdmin to exclude the UserProfileInline from the add view :
class LocalUserAdmin(UserAdmin):
inlines = (UserProfileInline, )
def get_formsets_with_inlines(self, request, obj=None):
for inline in self.get_inline_instances(request, obj):
# hide MyInline in the add view
if isinstance(inline, UserProfileInline) and obj is None:
continue
yield inline.get_formset(request, obj), inline
see https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_formsets_with_inlines
EDIT1: I tried doing sqlflush to reset everything, but that didn't help.
EDIT2: I am able to create a user and specify OtherModel as NULL, and then edit the user later to make othermodel an actual reference. The problem occurs when I specify a reference during user creation.
So in my app, which is hooked up with postgres, I'm trying to extend the User model that django provides with a new model called UserProfile. I want each User to be associated with another model I created. So here's my code:
models.py
.
.
.
class OtherModel(models.Model):
# model info
class UserProfile(models.Model):
user = models.OneToOneField(User)
othermodel = models.OneToOneField(OtherModel, null=True)
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile, created = UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
When I create a User from the django admin interface, I get the following error:
IntegrityError at /admin/auth/user/add/
duplicate key value violates unique constraint "planamocal_userprofile_user_id_key"
DETAIL: Key (user_id)=(23) already exists.
Everytime I try to make a new user, the user_id count keeps incrementing, which is weird because my actual user count stays the same.
Here's the backtrace:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/auth/user/add/
Django Version: 1.3.1
Python Version: 2.7.1
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'planamocal',
'django.contrib.admin']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
307. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
79. response = view_func(request, *args, **kwargs)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
197. return view(request, *args, **kwargs)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
28. return bound_func(*args, **kwargs)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
24. return func(self, *args2, **kwargs2)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/db/transaction.py" in inner
217. res = func(*args, **kwargs)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/contrib/auth/admin.py" in add_view
103. return super(UserAdmin, self).add_view(request, form_url, extra_context)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
28. return bound_func(*args, **kwargs)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
24. return func(self, *args2, **kwargs2)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/db/transaction.py" in inner
217. res = func(*args, **kwargs)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/contrib/admin/options.py" in add_view
885. self.save_formset(request, form, formset, change=False)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/contrib/admin/options.py" in save_formset
677. formset.save()
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/forms/models.py" in save
482. return self.save_existing_objects(commit) + self.save_new_objects(commit)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/forms/models.py" in save_new_objects
613. self.new_objects.append(self.save_new(form, commit=commit))
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/forms/models.py" in save_new
717. obj.save()
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/db/models/base.py" in save
460. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/db/models/base.py" in save_base
553. result = manager._insert(values, return_id=update_pk, using=using)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/db/models/manager.py" in _insert
195. return insert_query(self.model, values, **kwargs)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/db/models/query.py" in insert_query
1436. return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
791. cursor = super(SQLInsertCompiler, self).execute_sql(None)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
735. cursor.execute(sql, params)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/db/backends/util.py" in execute
34. return self.cursor.execute(sql, params)
File "/Users/AndyFang/Desktop/planamo/venv/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py" in execute
44. return self.cursor.execute(query, args)
Exception Type: IntegrityError at /admin/auth/user/add/
Exception Value: duplicate key value violates unique constraint "planamocal_userprofile_user_id_key"
DETAIL: Key (user_id)=(23) already exists.
How to fix this error?
The problem occurs because it appears you are trying to create a user profile and add the other model simultaneously in the admin.
Since the other model is a signal connected to the user creation, therefore, it is impossible.
Change the work flow such that you create the user, save user, create profile, save profile and add other model, save profile (in this order)