Django NOT NULL constraint failed: product_product.price - django

I am learning Django, and is following this online tutorial for creating forms.
https://www.youtube.com/watch?v=6oOHlcHkX2U&list=PLEsfXFp6DpzTD1BD1aWNxS2Ep06vIkaeW&index=23. Upon rendering in browser, I receive NOT NULL constraint failed: product_product.price.
In my models.py I have
from django.db import models
# Create your models here.
class Product(models.Model):
title = models.CharField(max_length = 200, null = False, blank = False)
description = models.TextField(null = True, blank = True)
price = models.DecimalField(decimal_places=0, max_digits = 10)
active = models.BooleanField(default = True)
def __str__(self):
return self.title
In my views.py under the same app I have
from django.shortcuts import render
from .forms import ProductForm
# Create your views here.
def productCreateView(request):
form = ProductForm(request.POST or None)
if form.is_valid:
print('form is valid now to saving')
print('\n\n')
form.save()
context = {'form' : form}
return render(request, '../templates/product_create.html', context=context)
I have tried to
python manage.py makemigrations
python manage.py migrate
when I tried to modify my price in my models.py e.g. by stating
price = models.DecimalField(decimal_places=0, max_digits = 10, blank = False, null = False)
Each time it says that there is nothing to migrate.
For the sake of learning, can anybody tell me what I am missing?
My complete error messages looks like below
[09/Mar/2020 23:24:41] "GET /create HTTP/1.1" 301 0
form is valid now to saving
Internal Server Error: /create/
Traceback (most recent call last):
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: NOT NULL constraint failed: product_product.price
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python\dimsumshop\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Python\dimsumshop\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python\dimsumshop\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python\dimsumshop\shop\product\views.py", line 11, in productCreateView
form.save()
File "C:\Python\dimsumshop\env\lib\site-packages\django\forms\models.py", line 459, in save
self.instance.save()
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\models\base.py", line 746, in save
force_update=force_update, update_fields=update_fields)
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\models\base.py", line 784, in save_base
force_update, using, update_fields,
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\models\base.py", line 887, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\models\base.py", line 926, in _do_insert
using=using, raw=raw,
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\models\query.py", line 1204, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\models\sql\compiler.py", line 1391, in execute_sql
cursor.execute(sql, params)
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\backends\utils.py", line 100, in execute
return super().execute(sql, params)
File "C:\Python\dimsumshop\env\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\dimsumshop\env\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:\Python\dimsumshop\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: product_product.price
[09/Mar/2020 23:24:41] "GET /create/ HTTP/1.1" 500 145386

Replace form.is_valid with form.is_valid() as proposed by Willem Van Onsem is the answer! Thanks!

Related

Django POST http://127.0.0.1:8000/create_member/ 500 (Internal Server Error)

i try to add usernames to my video chatting app and this error occured. I try to fetch create_member but this error occured. I try to solve many times but failed. Kindly Check it.
Uncaught (in promise) SyntaxError: Unexpected token. This error occured in console and i can't get my video and audio tracks.
Internal Server Error: /create_member/
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line
89, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 477, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such column: videoApp_roommember.name
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\hp\Desktop\ChattingApp\VideoChatting\videoApp\views.py", line 76, in createMember
member, created = RoomMember.objects.get_or_create(
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\manager.py", line
85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 657, in get_or_create
return self.get(**kwargs), False
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 492, in get
num = len(clone)
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 302, in __len__
self._fetch_all()
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 1507, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 57, in __iter__
results = compiler.execute_sql(
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\compiler.py",
line 1361, in execute_sql
cursor.execute(sql, params)
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line
103, in execute
return super().execute(sql, params)
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line
67, in execute
return self._execute_with_wrappers(
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line
80, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line
84, in _execute
with self.db.wrap_database_errors:
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line
89, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 477, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such column: videoApp_roommember.name
[11/Oct/2022 07:47:37] "POST /create_member/ HTTP/1.1" 500 141222
So, here is my views.py file:
#csrf_exempt
def createMember(request):
data = json.loads(request.body)
member, created = RoomMember.objects.get_or_create(
name=data['name'],
uid=data['UID'],
room_name=data['room_name']
)
return JsonResponse({'name':data['name']}, safe=False)
here is my script.js file
let createMember = async () => {
let response = await fetch('/create_member/', {
method:'POST',
headers: {
'Content-Type':'application/json'
},
body:JSON.stringify({'name':NAME, 'room_name':CHANNEL, 'UID':UID})
})
let member = await response.json()
return member
}
And here is models.py file
class RoomMember(models.Model):
name = models.CharField(max_length=200)
uid = models.CharField(max_length=1000)
room_name = models.CharField(max_length=200)
insession = models.BooleanField(default=True)
def __str__(self):
return self.name
In django's docs under migrations it says:
Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema.
So the error says
django.db.utils.OperationalError: no such column: videoApp_roommember.name
Which means the changes you made, which is adding name to the model, has not been migrated to take effect on the database table so whenever you make a query or try to create a room member the error above will be thrown because of not finding the name column in the DB.
So you need to:
Run python manage.py makemigrations to create the migrations file for the changes you made.
Run python manage.py migrate to make the updates to the database

Django doesn't create test database when running test

I read in Django document that a blank database will be created for testing. I am new to Django so I barely changed anything in setting.py and currently using Sqlite database. However, when I run python manage.py test, Django keep telling the user has been existed, so I tried changing the username for the created users in TestCase, run the test again and found out that the new users are created in the existing database. The test file is as bellow:
class UserTestCase(unittest.TestCase):
def setUp(self):
admin = User.objects.create(username="admin", password="1")
user1 = User.objects.create(username="user1", password="1")
user2 = User.objects.create(username="user2", password="1")
admin.following.add(user1)
admin.followers.add(user2)
def test_users_count(self):
self.assertEqual(User.objects.count()==3)
My model is as bellow:
class User(AbstractUser):
followers = models.ManyToManyField('self', related_name="following", symmetrical=False, through='Follow', through_fields=('followee', 'follower'))
def __str__(self):
return f"{self.username}"
def serialize(self):
return {
"id": self.id,
"username": self.username,
}
class Follow(models.Model):
followee = models.ForeignKey(
'User',
on_delete=models.CASCADE,
related_name='+'
)
follower = models.ForeignKey(
'User',
on_delete=models.CASCADE,
related_name='+'
)
def clean(self, *args, **kwargs):
if self.follower__id == self.followee__id:
raise ValidationError('Can not follow self.')
return super().clean(*args, **kwargs)
class Meta:
constraints = [
models.UniqueConstraint(fields=['follower', 'followee'], name='follow_once'),
models.CheckConstraint(check=~Q(follower=F('followee')), name='not_follow_self')
]
EDIT: Bellow is the output when I run python manage.py test
(env_web) PS C:\Users\HL94NVT\Programming\web_development\project4> python manage.py test
System check identified no issues (0 silenced).
EE
======================================================================
ERROR: test_following_count (network.tests.UserTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: network_user.username
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\HL94NVT\Programming\web_development\project4\network\tests.py", line 21, in setUp
admin = User.objects.create(username="admin1", password="1")
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\query.py", line 447, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save
super().save(*args, **kwargs)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 754, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 792, in save_base
force_update, using, update_fields,
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\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 "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 935, in _do_insert
using=using, raw=raw,
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\query.py", line 1254, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\sql\compiler.py", line 1397, in execute_sql
cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\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\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: network_user.username
======================================================================
ERROR: test_users_count (network.tests.UserTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: network_user.username
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\HL94NVT\Programming\web_development\project4\network\tests.py", line 21, in setUp
admin = User.objects.create(username="admin1", password="1")
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\query.py", line 447, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save
super().save(*args, **kwargs)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 754, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 792, in save_base
force_update, using, update_fields,
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\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 "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\base.py", line 935, in _do_insert
using=using, raw=raw,
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\query.py", line 1254, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\models\sql\compiler.py", line 1397, in execute_sql
cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\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\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\HL94NVT\Programming\web_development\env_web\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: network_user.username
----------------------------------------------------------------------
Ran 2 tests in 0.063s
Using django.test.TestCase instead of unittest.TestCase helps according to the document
https://docs.djangoproject.com/en/3.1/topics/testing/overview/
If your tests rely on database access such as creating or querying models, be sure to create your test classes as subclasses of django.test.TestCase rather than unittest.TestCase.
Using unittest.TestCase avoids the cost of running each test in a transaction and flushing the database, but if your tests interact with the database their behavior will vary based on the order that the test runner executes them. This can lead to unit tests that pass when run in isolation but fail when run in a suite.

Integrity Error django with UniqueConstraint

I have the following model snippet:
class InvoiceReference(TemplateMixin, models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
reference_prefix = models.CharField(
max_length=100,
validators=(RegexValidator(regex='^\S+$',
message='reference prefix must not include spaces'),)
)
reference_offset = models.PositiveIntegerField(default=0)
reference_suffix = models.CharField(
max_length=100,
validators=(RegexValidator(regex='^\S+$',
message='reference suffix must not include spaces'),)
)
reference_separator = models.CharField(max_length=1)
class Meta:
constraints = [
models.UniqueConstraint(fields=('user', 'reference_prefix', 'reference_suffix', 'reference_separator',), name='unique_reference')
]
The idea is to have it so that a no single user cannot use the same reference_prefix, reference_separator and reference_suffix together multiple times. (if different users use the same combination of reference_prefix, reference_separator and reference_suffix this is ok.)
I am currently using the django-admin model form, where I have excluded the user field and attach a user in save_model:
class InvoiceReferenceAdmin(admin.ModelAdmin):
model = InvoiceReference
exclude = ('user',)
def save_model(self, request, obj, form, change):
if not obj.pk:
obj.user = request.user
super().save_model(request=request, obj=obj, form=form, change=change)
however, this results in an 'Integrity Error' when I try to save the model.
Traceback:
Traceback (most recent call last):
File "django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "django/db/backends/sqlite3/base.py", line 383, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: invoice_invoice.user_id, invoice_invoice.reference_prefix, invoice_invoice.reference_suffix, invoice_invoice.reference_separator
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "django/contrib/admin/options.py", line 606, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "django/utils/decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "django/contrib/admin/sites.py", line 223, in inner
return view(request, *args, **kwargs)
File "django/contrib/admin/options.py", line 1645, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "django/utils/decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "django/utils/decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "django/contrib/admin/options.py", line 1529, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "django/contrib/admin/options.py", line 1572, in _changeform_view
self.save_model(request, new_object, form, not add)
File "/Users/leonhughes/dev/django/invoiceweb/invoice/admin.py", line 42, in save_model
super().save_model(request=request, obj=obj, form=form, change=change)
File "django/contrib/admin/options.py", line 1088, in save_model
obj.save()
File "django/db/models/base.py", line 741, in save
force_update=force_update, update_fields=update_fields)
File "django/db/models/base.py", line 779, in save_base
force_update, using, update_fields,
File "django/db/models/base.py", line 870, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "django/db/models/base.py", line 908, in _do_insert
using=using, raw=raw)
File "django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "django/db/models/query.py", line 1186, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "django/db/models/sql/compiler.py", line 1375, in execute_sql
cursor.execute(sql, params)
File "django/db/backends/utils.py", line 99, in execute
return super().execute(sql, params)
File "django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "django/db/backends/utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "django/db/backends/sqlite3/base.py", line 383, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: invoice_invoice.user_id, invoice_invoice.reference_prefix, invoice_invoice.reference_suffix, invoice_invoice.reference_separator
I have seen this in the django documentation
In general constraints are not checked during full_clean(), and do not
raise ValidationErrors. Rather you’ll get a database integrity error
on save(). UniqueConstraints without a condition (i.e. non-partial
unique constraints) are different in this regard, in that they
leverage the existing validate_unique() logic, and thus enable
two-stage validation. In addition to IntegrityError on save(),
ValidationError is also raised during model validation when the
UniqueConstraint is violated.
As I have no conditions set shouldn't a ValidationError be raised first?
One way to achieve a similar result as yours would be to make user a hidden field in your admin form and then override ModelAdmin.get_changeform_initial_data to pass the current user as the value for this hidden input.
This would mean that the user would be included in unique validation checks as the field would not be excluded from the form. When editing an existing object initial data is ignored so you shouldn't override any existing user relation
class InvoiceReferenceAdminForm(forms.ModelForm):
class Meta:
model = InvoiceReference
fields = '__all__'
widgets = {'user': forms.HiddenInput}
class InvoiceReferenceAdmin(admin.ModelAdmin):
model = InvoiceReference
form = InvoiceReferenceAdminForm
def get_changeform_initial_data(self, request):
return {'user': request.user}

Django one-one relation IntegrityError: UNIQUE constraint failed

I want to make a website which creates a 14 weeks therapy session for its users.
The course/therapy has a one to one relationship with the user and the therapist. And a many to one relationship with the weekly sessions model. When I simply created the course without creating the weekly sessions, everything worked fine. But when I added code for creating weekly sessions(in the same views function), it shows integrity error.
models.py :
class Therapist(models.Model):
name = models.CharField(max_length=20)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
contact = models.CharField(validators=[phone_regex], max_length=17,blank=True)
region=models.CharField(max_length=30,default='online')
def __unicode__(self):
return self.name
class UserProfile(models.Model):
user = models.OneToOneField(User)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
phone = models.CharField(validators=[phone_regex],max_length=17,blank=True)
age=models.IntegerField()
region=models.CharField(max_length=30)
def __unicode__(self):
return self.user.username
def get_region(self):
return self.region
class CBT_therapy(models.Model):
"""docstring for CBT_therapy : has one to one relationship with user and therapist.
Many to one relation with weekly session.
"""
start_date = models.DateField()
session_time=models.TimeField()
therapist=models.OneToOneField(Therapist)
user=models.OneToOneField(User,on_delete=models.CASCADE)
class WeeklySession(models.Model):
session_date=models.DateField()
session_time=models.TimeField()
week_no = models.IntegerField()
challenge=models.CharField(max_length=150)
therapy = models.ForeignKey(CBT_therapy)
class Challenge(models.Model):
title=models.CharField(max_length=150)
def __unicode__(self):
return self.title
Views.py :
def registerCBT(request):
if request.method == 'POST':
register_form = RegisterCBTForm(request.POST or None)
if register_form.is_valid():
start_date=register_form.cleaned_data['start_date']
session_time=register_form.cleaned_data['session_time']
user=request.user
username=UserProfile.objects.get(user=user)
region=username.get_region()
try:
therapist_name=Therapist.objects.get(region=region)
except :
therapist_name=Therapist.objects.get(region='online')
cbt=CBT_therapy(
user=user,
start_date=start_date,
session_time=session_time,
therapist=therapist_name
)
cbt.save(force_insert=True)
session_date=start_date
for challenge in Challenge.objects.all():
session_date = session_date + timedelta(days=7)
w=WeeklySession(
session_time =session_time,
session_date =session_date,
week_no=challenge.pk,
challenge=challenge.title,
therapy=cbt
)
w.save(force_insert=True)
else:
register_form = RegisterCBTForm()
return render(request,'register_for_cbt.html',{'register_form':register_form})
Traceback :
Traceback (most recent call last):
File "/home/tux/yes/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/home/tux/yes/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: CBT_cbt_therapy.therapist_id
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/tux/yes/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/home/tux/yes/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/tux/yes/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/tux/frames/CBT_therapy/CBT/views.py", line 63, in registerCBT
cbt.save(force_insert=True)
File "/home/tux/yes/lib/python3.6/site-packages/django/db/models/base.py", line 807, in save
force_update=force_update, update_fields=update_fields)
File "/home/tux/yes/lib/python3.6/site-packages/django/db/models/base.py", line 837, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/tux/yes/lib/python3.6/site-packages/django/db/models/base.py", line 923, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/tux/yes/lib/python3.6/site-packages/django/db/models/base.py", line 962, in _do_insert
using=using, raw=raw)
File "/home/tux/yes/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/tux/yes/lib/python3.6/site-packages/django/db/models/query.py", line 1076, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/tux/yes/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1107, in execute_sql
cursor.execute(sql, params)
File "/home/tux/yes/lib/python3.6/site-packages/django/db/backends/utils.py", line 80, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/tux/yes/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/home/tux/yes/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/tux/yes/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/tux/yes/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/home/tux/yes/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: CBT_cbt_therapy.therapist_id

django.db.utils.IntegrityError: NOT NULL constraint failed: chat_chat2.message

I try to built basic chat application in django using jquery. In my post view of views.py, I successfully get the message data but some how in c.save() i got an below error. i also try to debug passing default value but getting same error. i can't make it as a not null constraint.
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Chat2(models.Model):
user = models.ForeignKey(User)
message = models.CharField(max_length=500)
def __unicode__(self):
return self.message
chat.js
$('#msg_f').on('submit',function(event) {
event.preventDefault();
$.ajax({
datatype:"json",
url : '/login/post/',
type: 'POST',
data:{msgbox : $('#msg_box').val()},
success : function(data){
$('#msg_box').val('');
$('#msg_b').append('<div class="msg_right"><p class="msg">'+data.msgbox+'</p></div>');
}
});
});
views.py
def post(request):
if request.method=="POST":
msg = request.POST.get('msgbox',None)
c = Chat2(user=request.user,message=msg)
if msg != '':
c.save()
return JsonResponse({'msg':msg,'user':c.user.username})
else:
return HttpResponse("request must be post")
Error
[24/Jun/2017 09:21:45] "GET /login/login/chat_home/ HTTP/1.1" 200 3216
Internal Server Error: /login/post/
Traceback (most recent call last):
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 328, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: NOT NULL constraint failed: chat_chat2.message
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
response = get_response(request)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\django-tuto\login\chat\views.py", line 40, in post
c.save()
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\models\base.py", line 806, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\models\base.py", line 836, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\models\base.py", line 922, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\models\base.py", line 961, in _do_insert
using=using, raw=raw)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\models\query.py", line 1063, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\models\sql\compiler.py", line 1099, in execute_sql
cursor.execute(sql, params)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 80, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "C:\Users\Harshit\Anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 328, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: chat_chat2.message