I'm Using Django with a custom user model with custom UUID and custom user manager:
class CustomUser(AbstractUser):
id = models.UUIDField(primary_key=True, default=generate_id(), editable=False)
# ...
As you can see, I'm NOT using default=uuid4(). Instead I've made a function my on my own that uses uuid() to generate the custom id also using the timestamp:
from datetime import datetime as dt
from uuid import uuid1, uuid3, uuid4
def generate_id():
timestamp = str(dt.timestamp(dt.now()))
return uuid3(uuid4(),timestamp)
Now if I open the interactive shell: python manage.py shell and I call my function several time, this is what I get:
>>> generate_id()
UUID('bd8279f1-9b4b-3d7d-8932-f9e725f17045')
>>> generate_id()
UUID('0c2ec2ad-b062-3915-a9e9-22842c6f5ea2')
>>> generate_id()
UUID('2289202b-f252-3b27-bcae-cd44825bf4e0')
>>> generate_id()
UUID('88676ea9-4902-36ac-857d-929cb133089c')
>>> generate_id()
UUID('4a18b33e-12f0-3803-8ff0-0c4f0d1c849c')
but when I try creating 2 users:
from users.models import CustomUser
>>> one = CustomUser.objects.create_user(email='hhh#jaja.com',password='JJlsaks16112')
>>> two = CustomUser.objects.create_user(email='ttth#jija.com',password='JJlsaks16112')
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 73, in execute
return self.cursor.execute(query, args)
File "/usr/local/lib/python3.8/site-packages/MySQLdb/cursors.py", line 206, in execute
res = self._query(query)
File "/usr/local/lib/python3.8/site-packages/MySQLdb/cursors.py", line 319, in _query
db.query(q)
File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 259, in query
_mysql.connection.query(self, query)
MySQLdb._exceptions.IntegrityError: (1062, "Duplicate entry 'b448f583acfb31b7955926689b60f28a' for key 'PRIMARY'")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/foodbook24-api/users/models.py", line 23, in create_user
user.save()
File "/usr/local/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 67, in save
super().save(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 753, in save
self.save_base(using=using, force_insert=force_insert,
File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 790, in save_base
updated = self._save_table(
File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 895, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 933, in _do_insert
return manager._insert(
File "/usr/local/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 1254, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1397, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute
return super().execute(sql, params)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 73, in execute
return self.cursor.execute(query, args)
File "/usr/local/lib/python3.8/site-packages/MySQLdb/cursors.py", line 206, in execute
res = self._query(query)
File "/usr/local/lib/python3.8/site-packages/MySQLdb/cursors.py", line 319, in _query
db.query(q)
File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 259, in query
_mysql.connection.query(self, query)
django.db.utils.IntegrityError: (1062, "Duplicate entry 'b448f583acfb31b7955926689b60f28a' for key 'PRIMARY'")
If I go into the database and modify the id of my first custom user, I'm able to create a second user but as you can see from the screenshot below, the ID does not change!
I guess is a caching issue. Anyone as any idea of how can I solve it? (possibly keeping my custom UUID function) Thanks.
You are calling the function, and therefore the default=… parameter [Django-doc] will be set to the result of the response, not the function, and thus indeed, each time you generate an object, it will use that result.
You thus should pass a reference to the callable, not the result:
class CustomUser(AbstractUser):
# no parenthesis ↓
id = models.UUIDField(primary_key=True, default=generate_id, editable=False)
Related
I'm following the tutorial and I received a traceback ~>
Question.objects.all()Traceback (most recent call last): File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: polls_question The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/query.py", line 256, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/query.py", line 262, in __len__ self._fetch_all() File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql cursor.execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: polls_question >>> from django.utils import timezone >>> q = Question(question_text="What's new?", pub_date=timezone.now()) >>> q.save() Traceback (most recent call last): File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: polls_question The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/base.py", line 763, in save_base updated = self._save_table(b/backends/utils.py", line 84, in _execute File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/base.py", line 906, in _do_insert return manager._insert( File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/query.py", line 1270, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1416, in execute_sql cursor.execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params)django.db.utils.OperationalError: no such table: polls_question
I did the makemigrations and migrate, nothing changed or helped.
After I included at db.sqlite3 by hand the tables and that gave me another traceback ~>
Question.objects.all()Traceback (most recent call last): File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params)sqlite3.OperationalError: no such column: polls_question.question_textThe above exception was the direct cause of the following exception:Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/query.py", line 256, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/query.py", line 262, in __len__ self._fetch_all() File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql cursor.execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such column: polls_question.question_text >>> Question.objects.all() Traceback (most recent call last): File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: polls_question.question_text The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/query.py", line 256, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/query.py", line 262, in __len__ self._fetch_all() File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql cursor.execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/pingounica/.virtualenvs/django3/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params)django.db.utils.OperationalError: no such column: polls_question.question_text
that's my models.py ~>
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
and my manage.py ~>
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
What am I doing wrong?
Seems like you created your app using the command manage.py startapp polls but I see mysite in your manage.py
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
Django creates the table names in the database using a combination of the app name and the model name. In your case the app name is supposed to be polls I believe?, but for some reason the app name in your manage.py is mysite.
I suggest you start from scratch and try again with the manage.py startapp <app name> command, be careful of changing any references to the actual app name manually in any of the generated files.
from sabin.models import Task
>>> Task.objects.all()
<QuerySet []>
>>> t=Task(title="dhiraj")
t=Task(title="dhiraj")
t.save()
models.py file
from django.db import models
class Task(models.Model):
title=models.CharField(max_length=200)
completed=models.BooleanField(default=False)
created_at=models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Error says
Traceback (most recent call last):
File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: table sabin_task has no column named title
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\base.py", line 726, in save
self.save_base(using=using, force_insert=force_insert,
File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\base.py", line 763, in save_base
updated = self._save_table(
File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\base.py", line 868, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\base.py", line 906, in _do_insert
return manager._insert(
File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\query.py", line 1270, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\sql\compiler.py", line 1410, in execute_sql
cursor.execute(sql, params)
File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: table sabin_task has no column named title
Recently I migrated my local django + django-cms site to production server using following methods:
moved code to production server and populated db schema using makemigration and migrate commands
I exported the data using Pycharm's inbuilt database tool via "Dump data to File(s)" > "SQL-Insert-Statements.sql.groovy", the exported file had only insert statements and no other sql statement.
I copy pasted and executed these statements in query tool window using pgAdmin 4
I executed sql statements for reset sequences which I got from "python manage.py sqlsequencereset ..." command
Now after doing all this the website is working fine but on the admin side I can edit the page and it keeps the changes in database but throws error when I click on "publish page changes" button.
Here is the error:
django.db.utils.IntegrityError: duplicate key value violates unique constraint "cms_cmsplugin_path_4917bb44_uniq"
DETAIL: Key (path)=(0007) already exists.
Complete error stack:
[15/Jul/2020 21:13:40] "POST /en/admin/cms/page/45/en/publish/ HTTP/1.1" 500 25121
Internal Server Error: /en/admin/cms/page/45/en/publish/
Traceback (most recent call last):
File "/home/john/project1/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "cms_cmsplugin_path_4917bb44_uniq"
DETAIL: Key (path)=(0007) already exists.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/john/project1/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/john/project1/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/john/project1/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/john/project1/env/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/john/project1/env/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/home/john/project1/env/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 223, in inner
return view(request, *args, **kwargs)
File "/home/john/project1/env/lib/python3.6/site-packages/django/utils/decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "/home/john/project1/env/lib/python3.6/site-packages/django/views/decorators/http.py", line 40, in inner
return func(request, *args, **kwargs)
File "/usr/lib/python3.6/contextlib.py", line 52, in inner
return func(*args, **kwds)
File "/home/john/project1/env/lib/python3.6/site-packages/cms/admin/pageadmin.py", line 1125, in publish_page
all_published = page.publish(language)
File "/home/john/project1/env/lib/python3.6/site-packages/cms/models/pagemodel.py", line 987, in publish
self._copy_contents(public_page, language)
File "/home/john/project1/env/lib/python3.6/site-packages/cms/models/pagemodel.py", line 633, in _copy_contents
placeholder.copy_plugins(target_placeholder, language=language)
File "/home/john/project1/env/lib/python3.6/site-packages/cms/models/placeholdermodel.py", line 580, in copy_plugins
root_plugin=root_plugin,
File "/home/john/project1/env/lib/python3.6/site-packages/cms/utils/plugins.py", line 214, in copy_plugins_to_placeholder
new_plugin = CMSPlugin.add_root(instance=new_plugin)
File "/home/john/project1/env/lib/python3.6/site-packages/treebeard/mp_tree.py", line 625, in add_root
return MP_AddRootHandler(cls, **kwargs).process()
File "/home/john/project1/env/lib/python3.6/site-packages/treebeard/mp_tree.py", line 345, in process
newobj.save()
File "/home/john/project1/env/lib/python3.6/site-packages/djangocms_text_ckeditor/models.py", line 64, in save
super(AbstractText, self).save(*args, **kwargs)
File "/home/john/project1/env/lib/python3.6/site-packages/cms/models/pluginmodel.py", line 270, in save
super(CMSPlugin, self).save(*args, **kwargs)
File "/home/john/project1/env/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save
force_update=force_update, update_fields=update_fields)
File "/home/john/project1/env/lib/python3.6/site-packages/django/db/models/base.py", line 776, in save_base
parent_inserted = self._save_parents(cls, using, update_fields)
File "/home/john/project1/env/lib/python3.6/site-packages/django/db/models/base.py", line 807, in _save_parents
force_insert=parent_inserted,
File "/home/john/project1/env/lib/python3.6/site-packages/django/db/models/base.py", line 870, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/john/project1/env/lib/python3.6/site-packages/django/db/models/base.py", line 908, in _do_insert
using=using, raw=raw)
File "/home/john/project1/env/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/john/project1/env/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/john/project1/env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1368, in execute_sql
cursor.execute(sql, params)
File "/home/john/project1/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 99, in execute
return super().execute(sql, params)
File "/home/john/project1/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/john/project1/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/john/project1/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/john/project1/env/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/john/project1/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: duplicate key value violates unique constraint "cms_cmsplugin_path_4917bb44_uniq"
DETAIL: Key (path)=(0007) already exists.
something similar happened to me after migrating from sqlite to postgresql and I thought it was a problem with this.
But searching I found that it was a Treebeard 4.5 problem.
And the solution that worked for me was to Rollback to version 4.4.
https://github.com/django-cms/django-cms/issues/6980
Consider this snippet:
if fire_prim is not None:
print('Fire Primary is definitely not Null, here is proof: {}'.format(fire_prim))
fire_primary_obj = LifeSafety.objects.create(
name='Fire Primary',
store=store_obj,
phone_line=fire_prim,
phone_line_provider=an_provider)
We get the following output:
Fire Primary is definitely not Null, here is proof: +16077244546
Traceback (most recent call last):
File "C:\Python\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Python\lib\site-packages\django\db\backends\sqlite3\base.py", line 298, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: NOT NULL constraint failed: stores_lifesafety.phone_line
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\admin-dksc104694\Desktop\Dev\it-database\scripts\data.py", line 246, in update_lifesafety_devices
fire_primary_obj = LifeSafety.objects.create(name='Fire Primary', store=store_obj, phone_line=fire_prim, phone_line_provider=an_provider)
File "C:\Python\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python\lib\site-packages\django\db\models\query.py", line 413, in create
obj.save(force_insert=True, using=self.db)
File "C:\Python\lib\site-packages\django\db\models\base.py", line 718, in save
force_update=force_update, update_fields=update_fields)
File "C:\Python\lib\site-packages\django\db\models\base.py", line 748, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Python\lib\site-packages\django\db\models\base.py", line 831, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Python\lib\site-packages\django\db\models\base.py", line 869, in _do_insert
using=using, raw=raw)
File "C:\Python\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python\lib\site-packages\django\db\models\query.py", line 1136, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python\lib\site-packages\django\db\models\sql\compiler.py", line 1289, in execute_sql
cursor.execute(sql, params)
File "C:\Python\lib\site-packages\django\db\backends\utils.py", line 100, in execute
return super().execute(sql, params)
File "C:\Python\lib\site-packages\django\db\backends\utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Python\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Python\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Python\lib\site-packages\django\db\utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Python\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Python\lib\site-packages\django\db\backends\sqlite3\base.py", line 298, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: stores_lifesafety.phone_line
We can see with 100% certainty that the line just before object creation, fire_prim has a value of +16077244546 which should serve as the phone_line, but by the time it gets to creation its deleted somehow.
Here is my model for reference:
class LifeSafety(models.Model):
name = models.CharField(max_length=40, default='unspecified')
store = models.ForeignKey(Store, null=True, on_delete=models.SET_NULL)
phone_line = PhoneNumberField()
phone_line_provider = models.ForeignKey(Provider, null=True, on_delete=models.SET_NULL)
last_verification = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
Pre-Question:
I've allowed Null on the object and left the code to run &
unsurprisingly the objects are created, but phone_line is blank.
I am using the PhoneNumberField library.
I can "mock" this exact code from the shell & the object is created with the correct value every time.
The snippet above is exactly as shown, there is nothing in between the printing of fire_prim & the attempt at creation.
Post-Question:
Changed phone_line to a CharField rather than PhoneNumberField & the phone number is going through just fine. I'm opening an issue on their Github Repo as well.
Explicitly used the string as phone_line when creating the instance.
Verified once more that this can be done from shell without issue.
Input: LifeSafety.objects.create(name='Fire Primary', store=store, phone_line='+16077244546')
Output: LifeSafety: Fire Primary (Indicating QuerySet)
Interestingly when I do use the string explicitly on creation, the object does create with phone_line populated with that string, but I still get the error.
Input:
print('Fire Primary is definitely not Null, here is proof: {}'.format(fire_prim))
fire_primary_obj = LifeSafety.objects.create(
name = 'Fire Primary',
store = store_obj,
phone_line = '+16077244546',
phone_line_provider = an_provider
)
Output is the same stack trace as above (only name differences in diff checker).
I can go into admin and see that it was created, but I still get the NOT NULL constraint exception.
I had a really tough time to get fix this issue please help if you know this.
I have a project on django, It contain model with two fields, one is of type foreign key and other one is jsonfield. When it goes to save object in database,
it doesn't get saved instead it throw exception. I don't know what's the issue is. But issue is only specific to sqlite3 database. it is working fine with other databases. I am pasting stack trace and code. it throws exception on this line
student_record_obj.save()
Stack trace:
Internal Server Error: /tableapp/postdata/
Traceback (most recent call last):
File "C:\Python35\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Python35\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python35\lib\site-packages\django\db\backends\utils.py", line 100, in execute
return super().execute(sql, params)
File "C:\Python35\lib\site-packages\django\db\backends\utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Python35\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Python35\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Python35\lib\site-packages\django\db\utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Python35\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Python35\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.InterfaceError: Error binding parameter 1 - probably unsupported type.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python35\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "C:\Python35\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python35\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python35\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\Jdidi\Documents\Fresh\calendardjangoapp\tableapp\views.py", line 89, in posting_data
student_record_obj.save()
File "C:\Python35\lib\site-packages\django\db\models\base.py", line 729, in save
force_update=force_update, update_fields=update_fields)
File "C:\Python35\lib\site-packages\django\db\models\base.py", line 759, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Python35\lib\site-packages\django\db\models\base.py", line 842, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Python35\lib\site-packages\django\db\models\base.py", line 880, in _do_insert
using=using, raw=raw)
File "C:\Python35\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python35\lib\site-packages\django\db\models\query.py", line 1125, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python35\lib\site-packages\django\db\models\sql\compiler.py", line 1280, in execute_sql
cursor.execute(sql, params)
File "C:\Python35\lib\site-packages\django\db\backends\utils.py", line 104, in execute
sql = self.db.ops.last_executed_query(self.cursor, sql, params)
File "C:\Python35\lib\site-packages\django\db\backends\sqlite3\operations.py", line 136, in last_executed_query
params = self._quote_params_for_last_executed_query(params)
File "C:\Python35\lib\site-packages\django\db\backends\sqlite3\operations.py", line 125, in _quote_params_for_last_executed_query
return cursor.execute(sql, params).fetchone()
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.
[10/Jul/2018 23:01:32] "POST /tableapp/postdata/ HTTP/1.1" 500 18778
VIEWS.PY:
def posting_data(request):
if request.method == "POST":
response_ls = json.loads(request.POST.get('data', []))
final_ls = []
for dic in response_ls:
if dic and "csrfmiddlewaretoken" not in dic:
final_ls.append(dic)
try:
student_record_obj = StudentRecords.objects.get(user=request.user)
student_record_obj.data = final_ls
except StudentRecords.DoesNotExist:
attrs = {'user':request.user , 'data': final_ls}
student_record_obj = StudentRecords(**attrs)
student_record_obj.save()
return redirect('/tableapp/index')
According to the code above, final_ls variable is a list which is not insertable to database as such.
Dummp it as json string and then save it:
import json
.
.
final_ls = json.dumps(context)
attrs = {'user':request.user , 'data': final_ls}
student_record_obj = StudentRecords(**attrs)
Hope this helps.