Django table does not exist - django

I have a app in Django called webshopCatalog with the models.py. It is all in a development server, and I have previously dropped the mysql database followed by creating a new one since I was experimenting. The problem is, when I try to create a product now I get an error saying that the table does not exists (see the full error log when I click on the product link from admin). I have tried with python manage.py makemigrations and python manage.py migrate it doesn't solve the problem.
I also tried to comment out the model followed by making a python manage.py makemigrations and python manage.py migrate --fake and hereafter uncomment the model followed by repeating the steps without --fake, still it doesn't solve the problem.
from django.db import models
from django.db.models.fields.related import create_many_to_many_intermediary_model
from django.urls import reverse
class Product(models.Model):
name = models.CharField(max_length = 50, unique=True)
description = models.TextField()
allergic_note = models.CharField(max_length = 255, blank = True, null=True)
quantity = models.IntegerField(null = True, blank = True) #Used for campaign products to show how many items there is left
price = models.DecimalField(max_digits=9, decimal_places=0, default=0.00)
is_active = models.BooleanField(default = True)
is_deliverable = models.BooleanField(default = True)
image_path = models.ImageField(upload_to = 'productImages')
meta_keywords = models.CharField(max_length=255, help_text="comma delimited keywords text for SEO")
meta_description = models.CharField(max_length=255, help_text="SEO description content")
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
slug = models.SlugField(max_length=255, unique = True,
help_text="Unique text for url created from name")
printToKitchenName = models.CharField(max_length = 20, blank = True,
help_text= "Appears on receipt printer when printing to kitchen")
printToKitchen = models.BooleanField(default = True)
is_featured = models.BooleanField(default = False)
is_bestseller = models.BooleanField(default=False)
class Meta:
ordering = ['-created_at']
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("webshopCatalog-product", args=(self.slug,))
With the forms.py
from django import forms
from webshopCatalog.models import Product
class ProductAdminForm(forms.ModelForm):
class Meta:
model = Product
exclude = ['created_at', 'updated_at']
def clean_price(self):
if self.cleaned_data['price'] < 0: #We allow 0 to be included in case we want to give out free products
raise forms.ValidationError('Price cannot be negative value')
return self.cleaned_data['price']
and admin.py
from django.contrib import admin
# Register your models here.
from webshopCatalog.models import Product #Category
from webshopCatalog.forms import ProductAdminForm
class ProductAdmin(admin.ModelAdmin):
form = ProductAdminForm
#How the admin site will list products
list_display = ('name', 'price', 'created_at', 'updated_at',)
list_display_links = ('name',)
list_per_page = 50
ordering =['-name']
search_fields = ['name', 'description', 'meta_keywords', 'meta_description']
exclude = ('created_at', 'updated_at',)
#Sets up slug to be generated from product name
prepopulated_fields = {'slug' : ('name',)}
#Registers the product model with the admin interface
admin.site.register(Product, ProductAdmin)
The error I received when clicking on the product from the admin
System check identified no issues (0 silenced).
March 17, 2022 - 22:47:06
Django version 3.2.12, using settings 'website.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[17/Mar/2022 22:48:40] "GET /admin/ HTTP/1.1" 200 7433
Internal Server Error: /admin/webshopCatalog/product/
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 73, in execute
return self.cursor.execute(query, args)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/cursors.py", line 206, in execute
res = self._query(query)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/cursors.py", line 319, in _query
db.query(q)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/connections.py", line 259, in query
_mysql.connection.query(self, query)
MySQLdb._exceptions.ProgrammingError: (1146, "Table 'hiddendimsum_web_db.webshopcatalog_product' doesn't exist")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/admin/options.py", line 616, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 232, in inner
return view(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1697, in changelist_view
cl = self.get_changelist_instance(request)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/admin/options.py", line 749, in get_changelist_instance
sortable_by,
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/admin/views/main.py", line 100, in __init__
self.get_results(request)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/admin/views/main.py", line 235, in get_results
result_count = paginator.count
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/paginator.py", line 97, in count
return c()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 412, in count
return self.query.get_count(using=self.db)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py", line 519, in get_count
number = obj.get_aggregation(using, ['__count'])['__count']
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py", line 504, in get_aggregation
result = compiler.execute_sql(SINGLE)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql
cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 98, in execute
return super().execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 73, in execute
return self.cursor.execute(query, args)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/cursors.py", line 206, in execute
res = self._query(query)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/cursors.py", line 319, in _query
db.query(q)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/connections.py", line 259, in query
_mysql.connection.query(self, query)
django.db.utils.ProgrammingError: (1146, "Table 'hiddendimsum_web_db.webshopcatalog_product' doesn't exist")
[17/Mar/2022 22:48:42] "GET /admin/webshopCatalog/product/ HTTP/1.1" 500 202172

This problem is solved by
python manage.py makemigrations webshopCatalog
python manage.py migrate

Related

I am trying to delete a user from the django database but there ir a IntegrityError at /admin/auth/user/ error occurs

I want to delete a user from the database that django comes with, i entered the admin site using my superuser but when i try to delete any user manually, which i created for testing purposes, it gives the error y mentioned above, the traceback inserted below is the one from the logs.
Error
Traceback (most recent call last):
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 240, in _commit
return self.connection.commit()
sqlite3.IntegrityError: FOREIGN KEY constraint failed
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/contrib/admin/options.py", line 606, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/utils/decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/contrib/admin/sites.py", line 223, in inner
return view(request, *args, **kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/utils/decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/utils/decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/contrib/admin/options.py", line 1727, in changelist_view
response = self.response_action(request, queryset=cl.get_queryset(request))
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/contrib/admin/options.py", line 1397, in response_action
response = func(self, request, queryset)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/contrib/admin/actions.py", line 40, in delete_selected
modeladmin.delete_queryset(request, queryset)
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/contrib/admin/options.py", line 1098, in delete_queryset
queryset.delete()
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/models/query.py", line 711, in delete
deleted, _rows_count = collector.delete()
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/models/deletion.py", line 318, in delete
sender=model, instance=obj, using=self.using
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/transaction.py", line 240, in __exit__
connection.commit()
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 262, in commit
self._commit()
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 240, in _commit
return self.connection.commit()
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/lralcocer/PycharmProjects/MediTracker/venv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 240, in _commit
return self.connection.commit()
django.db.utils.IntegrityError: FOREIGN KEY constraint failed
[06/May/2020 02:47:33] "POST /admin/auth/user/ HTTP/1.1" 500 142907
These is my model
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserRegister(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
first_name = models.CharField(max_length=256, default='', blank=False,)
last_name = models.CharField(max_length=256, default='', blank=False)
email = models.EmailField(unique=True, blank=False,default='')
def __str__(self):
return self.user.username
This is my form
from django import forms
from .models import *
from django.contrib.auth.models import User
#Create your forms here!
class UserRegisterForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta():
model = User
fields = ('username','password')
class UserRegisterInfoForm(forms.ModelForm):
class Meta():
model = UserRegister
fields = ('first_name','last_name','email')
This is my view
def UserRegisterFormView(request):
registered = False
if request.method == 'POST':
userform = UserRegisterForm(data=request.POST)
userinfoform = UserRegisterInfoForm(data=request.POST)
if userform.is_valid() and userinfoform.is_valid():
user = userform.save()
user.set_password(user.password)
user.save()
profile = userinfoform.save(commit=False)
profile.user = user
profile.save()
registered = True
else:
print(userform.errors, userinfoform.errors)
else:
userform = UserRegisterForm
userinfoform = UserRegisterInfoForm
return render(request,'register/register.html'{'userform':userform,'userinfoform':userinfoform,'registered':registered})
You can delete the database except the init.py file. Then run makemigrations and migrate commands again.
If that dosen't fix it, then copy all the files in that folder into another folder, delete that folder, create a new one in your project directory, then pasted everything back in (be careful with your urls.py, don't forget to change them). Then run the makemigrations and migrate commands.

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.

Django Restful: How do I update my custom user model?

I'm building an API as part of a project for university, However, I have become stuck when working out how to make updates to my custom user model. At present I have a serializer for updating the profile, but when I try to update the table using the serializer, it falls over with error 1406: "Data too long for column 'title' at row 1". I'm not sure how to resolve this at present and was wondering if someone could point me in the right direction
update:
So it seems that I was getting the Data too long for column errors because The code I have is appending to the columns instead of just either altering them if the JSON contains data for the field, or leaving them if it does not. So once I'd tinkered with column lengths I was getting the following database row:
(None, 'Anthony'), (None, (None, 'Anthony')), 1, 0, 1, 1, 2019-01-01, ('a
test address', 'hello'), (None, None), (None, None), edd, (None,
'boy'), (None, 'there'), (None, None), (None, '282')
model in question:
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
title =models.CharField(_('Title'), max_length=8, null=True, blank=True)
first_name=models.CharField(_('first name(s)'), max_length=100, blank =True)
last_name=models.CharField(_('last name'), max_length=100, blank = True)
is_active=models.BooleanField(_('account active'), default=False)
is_driver = models.BooleanField(_('driver status'), default=False)
is_staff = models.BooleanField(_('staff status'), default =False)
is_admin = models.BooleanField(_('admin status'), default =False)
dob = models.DateField(auto_now_add= True, blank=True)
address_1=models.CharField(_('address line 1'),max_length=60, null=False, blank=False)
address_2=models.CharField(_('address line 2'),max_length=60, null=True, blank=True)
address_3=models.CharField(_('address line 3'),max_length=60, null=True, blank=True)
city = models.CharField(_('city'),max_length=60, null=False, blank=False)
county = models.CharField(_('county'),max_length=60, null=False, blank=False)
postcode = models.CharField(_('postcode'),max_length=8, blank=False, null=False)
phone_no = models.CharField(_('phone number'),max_length=50, null=True, blank=True)
mobile_no = models.CharField(_('mobile Number'),max_length=50,null=False, blank=False)
drivers_licence_number = models.CharField(max_length=30, null=True, blank=True)
taxi_licence_number=models.CharField(max_length=30, null=True, blank=True)
driver_photo=models.ImageField(blank=True)
date_joined=models.DateField(auto_now_add=True, blank=True)
last_update=models.DateField(auto_now_add=True, blank=True)
serializer in question:
class UserProfileSerializer (serializers.ModelSerializer):
model = User
id = serializers.IntegerField(read_only=True)
dob = serializers.DateField(read_only=True)
title=serializers.CharField(max_length=8, required=False)
first_name=serializers.CharField(max_length=80,required=False)
last_name=serializers.CharField(max_length=80,required=False)
address_1 = serializers.CharField(max_length=100, required=False)
address_2 = serializers.CharField(max_length=100,required=False)
address_3 = serializers.CharField(max_length=100,required=False)
postcode = serializers.CharField(max_length=10, required=False)
county = serializers.CharField(max_length=50, required=False)
city = serializers.CharField(max_length=50, required=False)
phone_no = serializers.CharField(required=False)
mobile_no = serializers.CharField(required=False)
def update (self, instance, validated_data):
instance.title= validated_data.get('title'), instance.title
instance.first_name = validated_data.get('first_name'), instance.first_name
instance.last_name = validated_data.get('last_name'), instance.first_name
instance.address_1 = validated_data.get('address_1'), instance.address_1
instance.address_2 = validated_data.get('address_2'), instance.address_2
instance.address_3 = validated_data.get('address_3'), instance.address_3
instance.postcode = validated_data.get('postcode'), instance.postcode
instance.county = validated_data.get('county'), instance.county
instance.phone_no = validated_data.get('phone_no'),instance.phone_no
instance.mobile_no = validated_data.get('mobile_no'), instance.mobile_no
instance.last_update = datetime.now()
instance.save()
return instance
View in question:
class UpdateProfile(APIView):
permission_classes=[permissions.IsAuthenticated]
def post(self, request, format=None):
user=request.user
print (user.id)
query_set=User.objects.get(id=user.id)
print("we got a queryset")
print(query_set)
serializer=UserProfileSerializer(query_set, data=request.data)
if serializer.is_valid():
profile = serializer.save()
if profile:
return Response(user.data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Trace from the server console:
Internal Server Error: /editprofile/ Traceback (most recent call
last): File
"C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\backends\utils.py",
line 85, in _execute
return self.cursor.execute(sql, params) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\backends\mysql\base.py",
line 71, in execute
return self.cursor.execute(query, args) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\cursors.py",
line 250, in execute
self.errorhandler(self, exc, value) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\connections.py",
line 50, in defaulterrorhandler
raise errorvalue File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\cursors.py",
line 247, in execute
res = self._query(query) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\cursors.py",
line 412, in _query
rowcount = self._do_query(q) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\cursors.py",
line 375, in _do_query
db.query(q) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\connections.py",
line 276, in query
_mysql.connection.query(self, query)
_mysql_exceptions.DataError: (1406, "Data too long for column 'title' at row 1")
The above exception was the direct cause of the following exception:
Traceback (most recent call last): File
"C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\core\handlers\exception.py",
line 34, in inner
response = get_response(request) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\core\handlers\base.py",
line 126, in _get_response
response = self.process_exception_by_middleware(e, request) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\core\handlers\base.py",
line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\views\decorators\csrf.py",
line 54, in wrapped_view
return view_func(*args, **kwargs) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\views\generic\base.py",
line 68, in view
return self.dispatch(request, *args, **kwargs) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\rest_framework\views.py",
line 495, in dispatch
response = self.handle_exception(exc) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\rest_framework\views.py",
line 455, in handle_exception
self.raise_uncaught_exception(exc) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\rest_framework\views.py",
line 492, in dispatch
response = handler(request, *args, **kwargs) File "C:\Users\clini\git\net302API\Test1\api\views.py", line 68, in post
profile = serializer.save() File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\rest_framework\serializers.py",
line 209, in save
self.instance = self.update(self.instance, validated_data) File "C:\Users\clini\git\net302API\Test1\api\serializers.py", line 137, in
update
instance.save() File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\contrib\auth\base_user.py",
line 73, in save
super().save(*args, **kwargs) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\models\base.py",
line 718, in save
force_update=force_update, update_fields=update_fields) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\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:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\models\base.py",
line 812, in _save_table
forced_update) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\models\base.py",
line 861, in _do_update
return filtered._update(values) > 0 File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\models\query.py",
line 712, in _update
return query.get_compiler(self.db).execute_sql(CURSOR) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\models\sql\compiler.py",
line 1383, in execute_sql
cursor = super().execute_sql(result_type) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\models\sql\compiler.py",
line 1065, in execute_sql
cursor.execute(sql, params) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\backends\utils.py",
line 100, in execute
return super().execute(sql, params) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\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:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\backends\utils.py",
line 77, in _execute_with_wrappers
return executor(sql, params, many, context) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\backends\utils.py",
line 85, in _execute
return self.cursor.execute(sql, params) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\utils.py",
line 89, in exit
raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\backends\utils.py",
line 85, in _execute
return self.cursor.execute(sql, params) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\django\db\backends\mysql\base.py",
line 71, in execute
return self.cursor.execute(query, args) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\cursors.py",
line 250, in execute
self.errorhandler(self, exc, value) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\connections.py",
line 50, in defaulterrorhandler
raise errorvalue File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\cursors.py",
line 247, in execute
res = self._query(query) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\cursors.py",
line 412, in _query
rowcount = self._do_query(q) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\cursors.py",
line 375, in _do_query
db.query(q) File "C:\Users\clini\MYDOCU~1\LICLIP~1\NET302~1\lib\site-packages\MySQLdb\connections.py",
line 276, in query
_mysql.connection.query(self, query) django.db.utils.DataError: (1406, "Data too long for column 'title' at row 1")
Did you maybe update the max_length of the title and did not migrate yet?
So To close this issue down, I found the solution. When I wrote the update method for my serializer i was writing them as
instance.fieldname =validated.data.get('input_name'),instance.fieldname
When they should have been
instance.fieldname =validated.data.get('input_name',instance.fieldname)
Thank you all for the help :)

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