Django one-one relation IntegrityError: UNIQUE constraint failed - django

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

Related

DataError('value too long for type character varying(40) on Heroku but not on development

My project works fine under the development but got this error on Heroku. The error occurs when user try to register. I use registration redux
Traceback (most recent call last):
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
The above exception (value too long for type character varying(40)
) was the direct cause of the following exception:
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs)
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\registration\views.py", line 53, in dispatch
return super().dispatch(request, *args, **kwargs)
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\edit.py", line 142, in post
return self.form_valid(form)
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\registration\views.py", line 56, in form_valid
new_user = self.register(form)
File "C:\Users\sdgy\SaaS\sdg\sdgenv\users\views.py", line 44, in register
new_user = super(Register, self).register(form_class)
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\registration\backends\default\views.py", line 96, in register
new_user = self.registration_profile.objects.create_inactive_user(
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\registration\models.py", line 185, in create_inactive_user
registration_profile = self.create_profile(
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\registration\models.py", line 211, in create_profile
profile.save()
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 726, in save
self.save_base(using=using, force_insert=force_insert,
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 763, in save_base
updated = self._save_table(
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\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\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 906, in _do_insert
return manager._insert(
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\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\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\compiler.py", line 1416, in execute_sql
cursor.execute(sql, params)
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\debug_toolbar\panels\sql\tracking.py", line 198, in execute
return self._record(self.cursor.execute, sql, params)
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\debug_toolbar\panels\sql\tracking.py", line 133, in _record
return method(sql, params)
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\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\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
Exception Type: DataError at /accounts/register/
Exception Value: value too long for type character varying(40)
I just made some updates including Python39 and Django 3. So maybe a lot have changed. But if the local environment is working fine, why does Heroku have issues?
My view
class Register(RegistrationView):
form_class = UserRegistrationForm
def register(self, form_class):
new_user = super(Register, self).register(form_class)
profile = Profile()
profile.user = new_user
profile.company = form_class.cleaned_data['company']
profile.title = form_class.cleaned_data['title']
profile.phone_number = form_class.cleaned_data['phone_number']
profile.address = form_class.cleaned_data['address']
profile.city = form_class.cleaned_data['city']
profile.province = form_class.cleaned_data['province']
profile.country = form_class.cleaned_data['country']
profile.postal = form_class.cleaned_data['postal']
profile.save()
template = get_template('registration/registration.txt')
context = {'name':new_user.first_name,'last':new_user.last_name,'company':profile.company,
'phone':profile.phone_number}
content = template.render(context)
return redirect('registration_complete')
My model
class Profile(models.Model):
user = models.OneToOneField(User, max_length=250,on_delete=models.CASCADE)
city=models.CharField(max_length=250, blank=True)
province=models.CharField(max_length=250, blank=True)
country=models.CharField(max_length=250,blank=True)
postal=models.CharField(max_length=7, blank=True)
address = models.CharField(max_length=250, blank=True)
company = models.CharField(max_length=250, blank=True)
title = models.CharField(max_length=250, blank=True)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format: '+6041234567'. Up to 15 digits allowed.")
phone_number = models.CharField(validators=[phone_regex], max_length=15, blank=True)
def __str__(self):
return 'Profile for user {}'.format(self.user.username)
I am learning here so please give me any pointers you might find helpful. Thanks.

Django NOT NULL constraint failed: product_product.price

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!

Unclear errors when trying to save data while overriding default 'create' method

Tried to write custom create method for my model, but run into some unclear errors.
Here is my code:
# models.py:
class ItemModel(models.Model):
item_id = models.CharField(max_length=10, primary_key=True)
name = models.CharField(max_length=40)
active = models.BooleanField(default=True)
def __str__(self):
return self.item_id
class ItemVersion(models.Model):
item_ver_id = models.CharField(max_length=13, primary_key=True)
item_ver = models.TextField()
config = models.TextField()
model = models.ForeignKey(ItemModel, on_delete=models.CASCADE, default=0)
session_id = models.CharField(max_length=40, default=0)
creation_date = models.DateTimeField(auto_now=False, auto_now_add=True)
finished = models.BooleanField(default=False)
def name(self):
return self.model.name
def __str__(self):
return str(self.model)
# serializers.py:
class ItemModelSerializer(serializers.ModelSerializer):
item_id = serializers.RegexField(regex='^\d{3}-\d{9}$', allow_blank=False)
name = serializers.CharField(min_length=6, max_length=50, allow_blank=False)
class Meta:
model = ItemModel
fields = '__all__'
class ItemVersionSerializer(serializers.ModelSerializer):
item_ver_id = serializers.RegexField(regex='^r\d{2}$', allow_blank=False)
session_id = serializers.RegexField(regex='^s\d{2}$', allow_blank=False)
link = serializers.SerializerMethodField()
name = serializers.SerializerMethodField()
config = serializers.CharField(min_length=6)
item_ver = serializers.CharField(min_length=6)
def get_name(self, obj):
return obj.name()
def get_link(self, obj):
link = 'https://example.net/' + str(obj.model)
+ str('-dyn') + '/?iv_id=' + str(obj.item_ver_id)
+ '&sessid=' + str(obj.session_id)
return link
# views.py:
class ItemModelViewSet(viewsets.ModelViewSet):
queryset = ItemModel.objects.all()
serializer_class = ItemModelSerializer
lookup_field = 'item_id'
class ItemVersionViewSet(viewsets.ModelViewSet):
serializer_class = ItemVersionSerializer
lookup_field = 'item_ver_id'
def get_queryset(self):
pass
def create(self, request, *args, **kwargs):
data = request.data
model = ItemModel.objects.get(item_id=data["model"])
item_version = ItemVersion.objects.create(
# model=model,
item_ver_id=data["item_ver_id"],
config=data["config"],
item_ver=data["item_ver"],
session_id=data["session_id"]
# finished=data["finished"]
)
item_version.model.add(model)
finished = True if data["finished"] else False
item_version.finished.add(finished)
item_version.save()
serializer = ItemVersionSerializer(item_version)
return Response(data)
For some reason, I keep getting FOREIGN KEY constraint failed and the session_id=data["session_id"] line is highlighted as the one where problem occurs nearby.
Any ideas how to solve this?
Edit: traceback:
Traceback (most recent call last):
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: FOREIGN KEY constraint failed
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/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/aqv/workspace/django_rest_fw/ct_test/environ/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/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/rest_framework/viewsets.py", line 116, in view
return self.dispatch(request, *args, **kwargs)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "/home/aqv/workspace/django_rest_fw/ct_test/core/views.py", line 47, in create
session_id=data["session_id"]
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/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/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/models/query.py", line 422, in create
obj.save(force_insert=True, using=self.db)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save
force_update=force_update, update_fields=update_fields)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/models/base.py", line 779, in save_base
force_update, using, update_fields,
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/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/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/models/base.py", line 908, in _do_insert
using=using, raw=raw)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/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/aqv/workspace/django_rest_fw/ct_test/environ/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/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1332, in execute_sql
cursor.execute(sql, params)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/backends/utils.py", line 99, in execute
return super().execute(sql, params)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/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/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/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/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: FOREIGN KEY constraint failed
The only foreign key I see is model there, and in your code you aren't passing it.
def create():
model = ItemModel.objects.get(item_id=data["model"])
item_version = ItemVersion.objects.create(
# model=model,
...
This will cause the FK constraint issue if you do not pass in a valid model instance or id because:
You have a default=0 for the model field
But no ItemModel with pk=0 exists in the databsae
If you want model to be nullable, then you can just add that to the FK definition:
class ItemVersion(models.Model):
...
model = models.ForeignKey(ItemModel, null=True, on_delete=CASCADE)
Later on I see you have these 2 lines:
item_version.model.add()
item_version.finished.add(finished).
These are both incorrect. add() doesn't work on boolean model field, and the .add() for an FK is only valid for many-to-many FKs, which are not being used here. The way you are passing them in the commented out sections is fine.
You can get a default value for the 'finished' flag by saying:
data.get('finished', False)
# this will throw a KeyError if "finished" isn't in the dict
True if data["finished"] else False
# this will not throw an error (but doesn't check the value of finished)
True if "finished" in data else False
Some other notes:
1) You use a ModelSerializer without a Meta class inside. Consider just using a standard serializer if you really want to do it by hand, or read up on ModelSerializers. If you use it correctly you shouldn't need a custom create method in the viewset.
2) default=<anything> is not a good idea on an FK. An FK should not generally have a default value (though there are some cases where its nice, like with pre-defined system data in constant tables)
3) You aren't using a serializer in your create method. You are accessing request.data directly. This will give you no validation, and no ability to say finished=BooleanField(default=False) and always get a value for serializer.validated_data['finished'].

Retrieve ForeignKey from views before saving in DJANGO

How can i retrieve the foreign key from the form child relationship, save it at the same time that I am saving the parent information on the same page.
I am currently working with two forms, the Parent and the child. The logic of the page is saving the name of a book and the name of the course it contains.
Ex: Book = "Learn data structure and algorithms",
Language = "Python"
models.py
class Entity(models.Model):
entity_name = models.CharField(max_length=250, blank=False)
owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='users')
class Meta:
verbose_name_plural = "Entities"
def __str__(self):
return self.entity_name
def get_absolute_url(self):
return reverse('snippets:password', kwargs={'pk': self.pk})
class Password(models.Model):
password_name = models.CharField(max_length=12, blank=False)
entity = models.ForeignKey(Entity, on_delete=models.CASCADE, related_name='passwords')
def __str__(self):
return self.password_name
forms.py
from django import forms
from snippets.models import Entity, Password
class EntityForm(forms.ModelForm):
class Meta:
model = Entity
fields = ('entity_name',)
class PasswordForm(forms.ModelForm):
class Meta:
model = Password
fields = ('password_name',)
views.py
def password_creation(request):
if request.method == 'POST':
form_one = EntityForm(request.POST)
form_two = PasswordForm(request.POST)
if form_one.is_valid():
entity_form = form_one.save(commit=False)
entity_form.owner = request.user
entity_form.save()
password_form = form_two.save(commit=False)
# HERE : what is the right way to retrieve name from PK
# owner is not part the Password table field therefore
# need to be changed to 'password_name'or 'entity'
# then, how to retrieve the field from the view??
password_form.owner = request.user
password_form.save()
return redirect('snippets:entity')
else:
form_one = EntityForm()
form_two = PasswordForm()
context = {
'form_one':form_one,
'form_two':form_two,
}
return render(request, 'snippets/create-password.html', context)
I have tried the codes above. The problem is that Django is saving the name of the "Book" but not the name of the "Language" in the database. The system also breaks and return this message : NOT NULL constraint failed: snippets_password.entity_id.
Any help would be much appreciated.
Traceback error
Traceback (most recent call last):
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/password_change/snippets/views.py", line 67, in password_creation
password_form.save()
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/base.py", line 729, in save
force_update=force_update, update_fields=update_fields)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/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 "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/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 "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/base.py", line 880, in _do_insert
using=using, raw=raw)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/query.py", line 1125, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1280, in execute_sql
cursor.execute(sql, params)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: snippets_password.entity_id
Your diagnosis is not at all correct. Password doesn't have an owner field, or in fact any relation with User. Its relationship is with Entity, and the error clearly states that it is the entity or that is missing. So you just have to assign the Entity you just created:
if form_one.is_valid() and form_two.is_valid():
entity = form_one.save(commit=False)
entity.owner = request.user
entity.save()
password = form_two.save(commit=False)
password.entity = entity
password.save()
Note, I added a check that that form_two is valid, and also renamed the objects: the result of calling form.save is not a form, but an instance of the model.

IntegrityError when sending multiple post requests

I am sending a post request for each tag
front-end is here:
handleOnClick() {
const { resource, csrf } = this.props;
let postFunc = (ele) => {
const label = ele.label.toLowerCase()
request
.post(`/bookmarks/groups/${label}`)
.set('X-CSRFToken', csrf)
.send(resource.id).then(() => {
console.log('we did it')
})
}
_(this.state.multiValue).forEach(postFunc)
Both post request seem to deliver, but any one after the first get and integrity error.
My view:
def post(self, request, slug):
"""Create a bookmark of the resource for the current user."""
# print request.user
to_add = Resource.objects.get(id=int(request.body))
try:
bm = Bookmark.objects.get(resource=to_add)
except Bookmark.DoesNotExist:
bm = Bookmark.objects.create(user=request.user, resource=to_add)
bookmark_group = BookmarkGroup.objects.get(name=slug)
bookmark_group.bookmarks.add(bm)
return JsonResponse({}, status=201, safe=False)
I am essentially checking to see if a bookmark is exists, and if it doesn't I create it.
Bookmark and group models:
class Bookmark(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
resource = models.ForeignKey("Resource", on_delete=models.CASCADE, related_name="bookmarks")
# meta
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class Meta:
unique_together = ('user', 'resource',)
ordering = ('resource',)
def __str__(self):
return "{} | {}".format(self.user, self.resource)
class BookmarkGroup(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(null=False, unique=True)
bookmarks = models.ManyToManyField(Bookmark, related_name='bookmarks', blank=True)
def __str__(self):
return self.name
I've included the stack-trace, and can include more code if needed:
Traceback (most recent call last):
File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/Users/path/to/my/app/views/bookmark_group.py", line 37, in post
bm = Bookmark.objects.create(user=request.user, resource=to_add)
File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/models/query.py", line 394, in create
obj.save(force_insert=True, using=self.db)
File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/models/base.py", line 806, in save
force_update=force_update, update_fields=update_fields)
File "/Users/path/to/my/venv/lib/python2.7/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 "/Users/path/to/my/venv/lib/python2.7/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 "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/models/base.py", line 961, in _do_insert
using=using, raw=raw)
File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/models/query.py", line 1061, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1099, in execute_sql
cursor.execute(sql, params)
File "/Users/path/to/my/venv/lib/python2.7/site-packages/debug_toolbar/panels/sql/tracking.py", line 164, in execute
return self._record(self.cursor.execute, sql, params)
File "/Users/path/to/my/venv/lib/python2.7/site-packages/debug_toolbar/panels/sql/tracking.py", line 106, in _record
return method(sql, params)
File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 80, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 101, in execute
return self.cursor.execute(query, args)
File "/Users/path/to/my/venv/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute
self.errorhandler(self, exc, value)
File "/Users/path/to/my/venv/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
IntegrityError: (1062, "Duplicate entry '1-2728' for key 'app_bookmark_user_id_resource_id_a01d1abf_uniq'")
From your traceback this line causing the exception,
bm = Bookmark.objects.create(user=request.user, resource=to_add)Ther error is because of you defined unique_together = ('user', 'resource',).
I would suggest you to change your views.py as below
def post(self, request, slug):
"""Create a bookmark of the resource for the current user."""
to_add = Resource.objects.get(id=int(request.body))
# Changes starts
bm, created = Bookmark.objects.get_or_create(user=request.user, resource=to_add)
bookmark_group = BookmarkGroup.objects.get(name=slug)
bookmark_group.bookmarks.add(bm)
return JsonResponse({}, status=201, safe=False)
or you can simply change ,
bm = Bookmark.objects.get(resource=to_add) to bm = Bookmark.objects.get(resource=to_add,user=request.user)