django.db.utils.OperationalError: no such table: main.authentication_user - python

I am getting the error mentioned in the title during my try to save some information to a postgres database.
My models.py script is the following:
from django.db import models
from django.contrib.auth import get_user_model
CustomUser = get_user_model()
class Event(models.Model):
user_id_event = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True)
dr_notice_period = models.IntegerField(blank=True, null=True)
dr_duration = models.IntegerField(blank=True, null=True)
dr_request = models.FloatField(blank=True, null=True)
CustomeUser is from the models.py of a custom authentication application:
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
demo = models.CharField(max_length=40)
My serializers.py script is the following:
from rest_framework import serializers
from vpp_optimization.models import Event
class EventSerializer(serializers.ModelSerializer):
class Meta:
model = Event
fields = ('__all__')
And my views.py where I am trying to add a specific event to the database is the following:
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from vpp_optimization.serializers import EventSerializer
#api_view(['POST'])
#permission_classes([IsAuthenticated,])
def event(request):
serializer = EventSerializer(data=request.data)
if serializer.is_valid():
serializer.save(user_id_event=request.user)
return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK)
else:
return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
The full error is the following:
Traceback (most recent call last):
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: main.authentication_user
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/rest_framework/decorators.py", line 50, in handler
return func(*args, **kwargs)
File "/root/energy_efficiency_flexibility_services/vpp_optimization/views.py", line 22, in event
serializer.save(user_id_event=request.user)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 205, in save
self.instance = self.create(validated_data)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 939, in create
instance = ModelClass._default_manager.create(**validated_data)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/models/query.py", line 447, in create
obj.save(force_insert=True, using=self.db)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/models/base.py", line 753, in save
self.save_base(using=using, force_insert=force_insert,
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/models/base.py", line 790, in save_base
updated = self._save_table(
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/models/base.py", line 895, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/models/base.py", line 933, in _do_insert
return manager._insert(
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/models/query.py", line 1254, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1397, in execute_sql
cursor.execute(sql, params)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute
return super().execute(sql, params)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: main.authentication_user
Any idea how can I fix it and why is it caused?

Related

I am getting "not NULL Constraint error" in my unit test only

I need help. My registration system is working perfectly fine when I run on a local server, but when I run my test. It fails. I don't understand why?
I am unable to figure out what is wrong, I have deleted the entire database and migrations. even I created the new app and did everything there. But still, I am getting this error.
My test_setup.py
from rest_framework.test import APITestCase
from django.urls import reverse
class TestSetup(APITestCase):
def setUp(self):
self.register_url = '/register/'
self.user_data = {"Username":"frontend123", "First name":"Frontend", "Last
name":"Developer", "Password":"bitspro##1", "Confirm
password":"bitspro##1","Email":"rida#bitspro.com","Date of
birth":"1997-12-27"}
return super().setUp()
def tearDown(self):
return super().tearDown()
My testViews.py
from authentication.models import User
from authentication.tests.test_setup import TestSetup
class TestViews(TestSetup):
def test_user_cannot_register_without_any_data(self):
res = self.client.post(self.register_url)
self.assertEqual(res.status_code, 400)
def test_user_can_register_correctly(self):
res = self.client.post(self.register_url, self.user_data, format="json")
self.assertEqual(res.status_code, 201)
My view.py (I am testing registration system only
from rest_framework.response import Response
from rest_framework.views import APIView
from authentication.models import User as Client
class Register(APIView):
def post(self, request):
username = request.data.get('Username')
first_name = request.data.get('First name')
last_name = request.data.get('Last name')
password = request.data.get('Password')
confirm_password = request.data.get('Confirm password')
date_of_birth = request.data.get('Date of birth')
email = request.data.get('Email')
if password == confirm_password:
if Client.objects.filter(username = username).exists():
return Response({"message": "this username already exist"}, 400)
elif Client.objects.filter(email = email).exists():
return Response({"message": "This email-address is already taken"}, 400)
else:
user= Client.objects.create(username = username, password =password, email=email,
date_of_birth=date_of_birth)
user.save()
return Response({"message":"User has been created"}, 201)
else:
return Response({"message": "Try it again"}, 404)
my urls.py
from django.urls import path
from authentication.views import Login, Logout, Register, Password_Reset
urlpatterns = [
path('register/', Register.as_view(), name = "register"),
]
My models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
email = models.EmailField(verbose_name="Email", max_length=60, unique=True)
date_of_birth= models.DateField(verbose_name="Date of Birth", max_length=10)
def __str__(self):
return self.username
I would really appreciate your help
my error
(venv) PS C:\Users\Lenovo\Documents\GitHub\E-commerce\garments> python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.E
======================================================================
ERROR: test_user_cannot_register_without_any_data (authentication.tests.test_views.TestViews)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: NOT NULL constraint failed: authentication_user.password
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\garments\authentication\tests\test_views.py", line 8, in test_user_cannot_register_without_any_data
res = self.client.post(self.register_url)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\rest_framework\test.py", line 295, in post
response = super().post(
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\rest_framework\test.py", line 209, in post
return self.generic('POST', path, data, content_type, **extra)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\rest_framework\test.py", line 233, in generic
return super().generic(
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\test\client.py", line 473, in generic
return self.request(**r)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\rest_framework\test.py", line 285, in request
return super().request(**kwargs)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\rest_framework\test.py", line 237, in request
request = super().request(**kwargs)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\test\client.py", line 719, in request
self.check_exception(response)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\test\client.py", line 580, in check_exception
raise exc_value
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\garments\authentication\views.py", line 38, in post
user= Client.objects.create(username = username, password =password, email=email, date_of_birth=date_of_birth)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\db\models\query.py", line 453, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save
super().save(*args, **kwargs)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\db\models\base.py", line 726, in save
self.save_base(using=using, force_insert=force_insert,
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\db\models\base.py", line 763, in save_base
updated = self._save_table(
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\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\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\db\models\base.py", line 906, in _do_insert
return manager._insert(
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\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\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1416, in execute_sql
cursor.execute(sql, params)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\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\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: authentication_user.password
----------------------------------------------------------------------
Ran 2 tests in 0.083s
FAILED (errors=1)
Destroying test database for alias 'default'..

DatabaseError: value too long for type character varying(20)

Solution:- I had deleted my migration .py files which caused this problem. Creating a new app with the same code works now.
I am not sure why i get a varying(20) error even when the max_length I've set is 200 for a CharField
I looked at all the other posts and all of them had an issue with the length of the value.
However, even if i enter "abc" in the name field it gives me this error. Any help is appreciated. Thanks!
Django Version: 3.1.5
Python Version: 3.8.5
from django.db import models
from django.contrib.gis.db import models
from django.db.models import Manager as GeoManager
# Create your models here.
class Incidences(models.Model):
name = models.CharField(max_length=200)
location = models.PointField(srid=4326)
objects = GeoManager()
def _str_(self):
return self.name
Traceback (most recent call last):
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\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(20)
) was the direct cause of the following exception:
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\contrib\admin\sites.py", line 233, in inner
return view(request, *args, **kwargs)
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\contrib\admin\options.py", line 1653, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\contrib\admin\options.py", line 1534, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\contrib\admin\options.py", line 1580, in _changeform_view
self.save_model(request, new_object, form, not add)
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\contrib\admin\options.py", line 1093, in save_model
obj.save()
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\db\models\base.py", line 753, in save
self.save_base(using=using, force_insert=force_insert,
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\db\models\base.py", line 790, in save_base
updated = self._save_table(
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\db\models\base.py", line 895, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\db\models\base.py", line 933, in _do_insert
return manager._insert(
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\db\models\query.py", line 1254, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\db\models\sql\compiler.py", line 1397, in execute_sql
cursor.execute(sql, params)
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\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\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\anuj\geo_django_tutorial\tutorial_geodjango\lifeingis\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
Exception Type: DataError at /admin/reporter/incidences/add/
Exception Value: value too long for type character varying(20)

Keep getting "FOREIGN KEY constraint failed" in Django

I am new to django and i am making a multivendor ecommerce website for my final year project. for the past three hours i keep having the foreingnkey constraints error when i want to add products.
please i need someone to help me and solve the problem. i added the traceback and forms.py .
views.py
def AddProduct(request):
"""this page will be used for adding products"""
if request.method =='POST':
form=ProductForm(request.POST)
if form.is_valid():
model=User
user=form.save()
return HttpResponseRedirect('/becomeaseller/DashBoard')
else:
form=ProductForm()
context={'form':form}
return render(request, 'app/addproduct.html',context)
return HttpResponse("enter the details and description of your products")
models.py
class User(AbstractUser):
is_customer = models.BooleanField(default=False)
is_seller = models.BooleanField(default=False)
class Product_Details(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
product_name=models.CharField(max_length=100)
category=models.ForeignKey(Category, on_delete=models.CASCADE)
product_image=models.ImageField(null=True)
product_description=models.CharField(max_length=100)
product_price=models.IntegerField()
product_quantity=models.IntegerField(default=1)
shop_name=models.CharField(max_length=100)
shop_location=models.CharField(max_length=100)
shop_description=models.CharField(max_length=100)
def __str__(self):
return self.product_name
forms.py
class ProductForm(ModelForm):
class Meta:
model=Product_Details
fields=['product_name','product_price','product_description','category']
traceback:
Internal Server Error: /becomeaseller/DashBoard/AddProduct
Traceback (most recent call last):
File "C:\users\mustapha\desktop\ecommerce\ecommerce\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\users\mustapha\desktop\ecommerce\ecommerce\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, 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 "C:\users\mustapha\desktop\ecommerce\ecommerce\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\users\mustapha\desktop\ecommerce\ecommerce\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\users\mustapha\desktop\ecommerce\ecommerce\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\users\mustapha\desktop\ecommerce\ecommerce\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\users\mustapha\desktop\ecommerce\multivendor\app\views.py", line 100, in AddProduct
user=form.save()
File "C:\users\mustapha\desktop\ecommerce\ecommerce\lib\site-packages\django\forms\models.py", line 460, in save
self.instance.save()
File "C:\users\mustapha\desktop\ecommerce\ecommerce\lib\site-packages\django\db\models\base.py", line 754, in save
force_update=force_update, update_fields=update_fields)
File "C:\users\mustapha\desktop\ecommerce\ecommerce\lib\site-packages\django\db\models\base.py", line 792, in save_base
force_update, using, update_fields,
File "C:\users\mustapha\desktop\ecommerce\ecommerce\lib\site-packages\django\db\models\base.py", line 895, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "C:\users\mustapha\desktop\ecommerce\ecommerce\lib\site-packages\django\db\models\base.py", line 935, in _do_insert
using=using, raw=raw,
File "C:\users\mustapha\desktop\ecommerce\ecommerce\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\users\mustapha\desktop\ecommerce\ecommerce\lib\site-packages\django\db\models\query.py", line 1254, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\users\mustapha\desktop\ecommerce\ecommerce\lib\site-packages\django\db\models\sql\compiler.py", line 1397, in execute_sql
cursor.execute(sql, params)
File "C:\users\mustapha\desktop\ecommerce\ecommerce\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\users\mustapha\desktop\ecommerce\ecommerce\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\mustapha\desktop\ecommerce\ecommerce\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrapper
s
return executor(sql, params, many, context)
File "C:\users\mustapha\desktop\ecommerce\ecommerce\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\users\mustapha\desktop\ecommerce\ecommerce\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\users\mustapha\desktop\ecommerce\ecommerce\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\users\mustapha\desktop\ecommerce\ecommerce\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: FOREIGN KEY constraint failed
There are some changes u can make for instance, user should be a foreign key in Products model instead of being primary key since I believe a user can add multiple products
So the the model us:
class Product_Details(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
...
The for the AddProduct method
def AddProduct(request):
"""this page will be used for adding products"""
if request.method =='POST':
form=ProductForm(request.POST)
if form.is_valid():
user=request.user
form.save(user=user)
return HttpResponseRedirect('/becomeaseller/DashBoard')
else:
form=ProductForm()
context={'form':form}
return render(request, 'app/addproduct.html',context)

Django Custom User UUID Duplicated (cached?)

I'm Using Django with a custom user model with custom UUID and custom user manager:
class CustomUser(AbstractUser):
id = models.UUIDField(primary_key=True, default=generate_id(), editable=False)
# ...
As you can see, I'm NOT using default=uuid4(). Instead I've made a function my on my own that uses uuid() to generate the custom id also using the timestamp:
from datetime import datetime as dt
from uuid import uuid1, uuid3, uuid4
def generate_id():
timestamp = str(dt.timestamp(dt.now()))
return uuid3(uuid4(),timestamp)
Now if I open the interactive shell: python manage.py shell and I call my function several time, this is what I get:
>>> generate_id()
UUID('bd8279f1-9b4b-3d7d-8932-f9e725f17045')
>>> generate_id()
UUID('0c2ec2ad-b062-3915-a9e9-22842c6f5ea2')
>>> generate_id()
UUID('2289202b-f252-3b27-bcae-cd44825bf4e0')
>>> generate_id()
UUID('88676ea9-4902-36ac-857d-929cb133089c')
>>> generate_id()
UUID('4a18b33e-12f0-3803-8ff0-0c4f0d1c849c')
but when I try creating 2 users:
from users.models import CustomUser
>>> one = CustomUser.objects.create_user(email='hhh#jaja.com',password='JJlsaks16112')
>>> two = CustomUser.objects.create_user(email='ttth#jija.com',password='JJlsaks16112')
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 73, in execute
return self.cursor.execute(query, args)
File "/usr/local/lib/python3.8/site-packages/MySQLdb/cursors.py", line 206, in execute
res = self._query(query)
File "/usr/local/lib/python3.8/site-packages/MySQLdb/cursors.py", line 319, in _query
db.query(q)
File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 259, in query
_mysql.connection.query(self, query)
MySQLdb._exceptions.IntegrityError: (1062, "Duplicate entry 'b448f583acfb31b7955926689b60f28a' for key 'PRIMARY'")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/foodbook24-api/users/models.py", line 23, in create_user
user.save()
File "/usr/local/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 67, in save
super().save(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 753, in save
self.save_base(using=using, force_insert=force_insert,
File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 790, in save_base
updated = self._save_table(
File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 895, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 933, in _do_insert
return manager._insert(
File "/usr/local/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 1254, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1397, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute
return super().execute(sql, params)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 73, in execute
return self.cursor.execute(query, args)
File "/usr/local/lib/python3.8/site-packages/MySQLdb/cursors.py", line 206, in execute
res = self._query(query)
File "/usr/local/lib/python3.8/site-packages/MySQLdb/cursors.py", line 319, in _query
db.query(q)
File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 259, in query
_mysql.connection.query(self, query)
django.db.utils.IntegrityError: (1062, "Duplicate entry 'b448f583acfb31b7955926689b60f28a' for key 'PRIMARY'")
If I go into the database and modify the id of my first custom user, I'm able to create a second user but as you can see from the screenshot below, the ID does not change!
I guess is a caching issue. Anyone as any idea of how can I solve it? (possibly keeping my custom UUID function) Thanks.
You are calling the function, and therefore the default=… parameter [Django-doc] will be set to the result of the response, not the function, and thus indeed, each time you generate an object, it will use that result.
You thus should pass a reference to the callable, not the result:
class CustomUser(AbstractUser):
# no parenthesis &downarrow;
id = models.UUIDField(primary_key=True, default=generate_id, editable=False)

Error in Django while adding a table on admin page

I'm making a simple booking app in Django. I've made a model where I'll store booking data for each day of the week and tried to add a table based on it on admin page. But when I click "save", I receive an error:
Traceback (most recent call last):
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
The above exception (no such table: baseapp_bookingmodel) was the direct cause of the following exception:
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\contrib\admin\sites.py", line 233, in inner
return view(request, *args, **kwargs)
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\contrib\admin\options.py", line 1653, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\contrib\admin\options.py", line 1534, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\contrib\admin\options.py", line 1580, in _changeform_view
self.save_model(request, new_object, form, not add)
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\contrib\admin\options.py", line 1093, in save_model
obj.save()
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\db\models\base.py", line 754, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\db\models\base.py", line 792, in save_base
force_update, using, update_fields,
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\db\models\base.py", line 895, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\db\models\base.py", line 935, in _do_insert
using=using, raw=raw,
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\db\models\query.py", line 1249, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1397, in execute_sql
cursor.execute(sql, params)
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\katja\PycharmProjects\django\venv\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\katja\PycharmProjects\django\venv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute
return Database.Cursor.execute(self, query, params)
Exception Type: OperationalError at /admin/baseapp/bookingmodel/add/
Exception Value: no such table: baseapp_bookingmodel
Any ideas why this happens? Earlier I received the same error when I tried to migrate some changes in the model, but it was fixed by deleting the database and migrations and making them again. I also get the same error when I try to reference the model on pages.
models.py:
from django.db import models
import sys
sys.path.append('C:/Users/katja/PycharmProjects/django/taskmanager')
def empty_data():
return [[0 for i in range(7)] for j in range(5)]
def empty_title():
return 'Monday'
class BookingModel(models.Model):
title = models.CharField(max_length=16, default=empty_title())
data = models.TextField(default=empty_data())
def __str__(self):
return self.title
class Meta:
verbose_name = 'Booking'
verbose_name_plural = 'Booking'
You should do migrations:
python manage.py makemigrations
python manage.py migrate
Your database has not table for this model.

Categories