When trying to create an account number, I get an IntegrityError: FOREIGN KEY constraint failed - django-models

I want that when creating an account number, the owner of the account be the current logged-in user.
I have read about foreign key constraints but do not know what constraint the CustomUser class is having to conflict the creation of an account number.
I have tried setting on_delete to CASCADE but still it throws the IntegrityError
Please help. Thanks.
My models.py
class CustomUser(TrackingModel, AbstractUser, PermissionsMixin):
GENDER = (
("F", "Female"),
("M", "Male"),
("NS", "Not Specified"),
)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
phone = models.CharField(max_length=20)
gender = models.CharField(max_length=6, choices=GENDER)
USERNAME_FIELD = "username"
REQUIRED_FIELDS = [
"phone",
]
#property
def token(self):
token = jwt.encode(
{
"username": self.username,
"email": self.email,
"exp": datetime.utcnow() + timedelta(hours=24),
},
settings.SECRET_KEY,
algorithm="HS256",
)
return token
def __str__(self):
return self.username
class Accountnumber(TrackingModel):
TYPE = (
("momo", "MTN Mobile Money"),
("om", "Orange Money"),
("visa", "Visa"),
("paypal", "Paypal"),
)
number = models.AutoField(primary_key=True, editable=False, default=9999)
type = models.CharField(
max_length=10,
choices=TYPE,
null=True,
default="momo",
)
customuser = models.ForeignKey(
CustomUser,
related_name="acc_no_user",
on_delete=models.CASCADE,
)
cdate = models.DateTimeField(auto_now_add=True)
enddate = models.DateTimeField(auto_now_add=True)
transactions = models.ForeignKey(
"Transaction",
related_name="acc_no_transactions",
on_delete=models.CASCADE,
default="2",
)
balance = models.PositiveIntegerField(
null=True,
blank=True,
default=00,
)
def __str__(self):
return self.number
My views.py:
class CreateAccountnumberAPIView(CreateAPIView):
serializer_class = AccountnumberSerializer
permission_classes = {
IsAuthenticated,
}
def perform_create(self, serializer):
return serializer.save(user=self.request.user)
My serializers.py:
class AccountnumberSerializer(serializers.ModelSerializer):
class Meta:
model = Accountnumber
fields = (
"number",
"type",
"cdate",
"enddate",
"transactions",
"balance",
)
My stacktrace shows at perform_create() at views.py:
Internal Server Error: /api/v1/wallet/v1/account
Traceback (most recent call last):
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\utils.py", line 98, in inner
return func(*args, **kwargs)
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\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\views\generic\base.py", line 84, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\rest_framework\generics.py", line 190, in post
return self.create(request, *args, **kwargs)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\rest_framework\mixins.py", line 19, in create
self.perform_create(serializer)
File "C:\Users\USER\Documents\Dev\API\grand\wallet\views.py", line 69, in perform_create
return serializer.save(customuser=self.request.user)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\rest_framework\serializers.py", line
212, in save
self.instance = self.create(validated_data)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\rest_framework\serializers.py", line
962, in create
instance = ModelClass._default_manager.create(**validated_data)
File "C:\Users\USER\Documents\Dev\API\grand\.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\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\models\query.py", line 514, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\models\base.py", line 806,
in save
self.save_base(
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\models\base.py", line 857,
in save_base
updated = self._save_table(
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\models\base.py", line 1000, in _save_table
results = self._do_insert(
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\models\base.py", line 1041, in _do_insert
return manager._insert(
File "C:\Users\USER\Documents\Dev\API\grand\.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\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\models\query.py", line 1434, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\models\sql\compiler.py", line 1632, in execute_sql
self.connection.ops.fetch_returned_insert_columns(
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\backends\base\operations.py", line 208, in fetch_returned_insert_columns
return cursor.fetchone()
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\utils.py", line 97, in inner
with self:
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\USER\Documents\Dev\API\grand\.venv\lib\site-packages\django\db\utils.py", line 98, in inner
return func(*args, **kwargs)
django.db.utils.IntegrityError: FOREIGN
KEY constraint failed
[13/Jan/2023 04:19:51] "POST /api/v1/wallet/v1/account HTTP/1.1" 500 183218

In your perform_create function you do the following:
def perform_create(self, serializer):
return serializer.save(user=self.request.user)
So you're saving the user variable to the user that made this request. That is fine, however, in your Accountnumber model, you store the user in the customuser field, not the user field.
Try to set your perform_create function to the following:
def perform_create(self, serializer):
return serializer.save(customuser=self.request.user)

All through, comments from my search for the answer have been that the IntegrityError of ForeignKey constriant failed mostly arises from the fact that you are trying to use a foreign key that does not yet exist and it was my case.
When creating an account number, I asked in my models.py that the field transactions be linked to the Transaction table foreign key WHICH DID NOT EXIST YET.
I, therefore, replaced the transaction field from referring to a ForeignKey to making it a CharField where I used the choices option and it worked.
Thanks, #Pavel Vergeev for editing my code
Thanks, #Ridape for pointing out an error which turns out was not the reason for the IntegrityError I was facing.

Related

I cann't creat new table in sqlite3 from django

When I added new string in models.py his tables did't create in sqlite3. What I do wrong, again :)
python manage.py makemigrations
python manage.py migrate - I did!
It's happend, when I don't input templates information after messege:
Please enter the default value now as valid Python.
The datetime and django.utils.timezone module are available so you can do e.g. timezone.now.
I imputed just 1 and enter. After thet it broke.
If you need different information give me know, please.
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/meetups/meetup/add/
Django Version: 3.2.8
Python Version: 3.10.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'meetups']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "C:\install\Projects_1\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\install\Projects_1\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
The above exception (table meetups_meetup has no column named enormus) was the direct cause of the following exception:
File "C:\install\Projects_1\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\install\Projects_1\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\install\Projects_1\env\lib\site-packages\django\contrib\admin\options.py", line 616, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\install\Projects_1\env\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\install\Projects_1\env\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\install\Projects_1\env\lib\site-packages\django\contrib\admin\sites.py", line 232, in inner
return view(request, *args, **kwargs)
File "C:\install\Projects_1\env\lib\site-packages\django\contrib\admin\options.py", line 1657, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "C:\install\Projects_1\env\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\install\Projects_1\env\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\install\Projects_1\env\lib\site-packages\django\contrib\admin\options.py", line 1540, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\install\Projects_1\env\lib\site-packages\django\contrib\admin\options.py", line 1586, in _changeform_view
self.save_model(request, new_object, form, not add)
File "C:\install\Projects_1\env\lib\site-packages\django\contrib\admin\options.py", line 1099, in save_model
obj.save()
File "C:\install\Projects_1\env\lib\site-packages\django\db\models\base.py", line 726, in save
self.save_base(using=using, force_insert=force_insert,
File "C:\install\Projects_1\env\lib\site-packages\django\db\models\base.py", line 763, in save_base
updated = self._save_table(
File "C:\install\Projects_1\env\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:\install\Projects_1\env\lib\site-packages\django\db\models\base.py", line 906, in _do_insert
return manager._insert(
File "C:\install\Projects_1\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\install\Projects_1\env\lib\site-packages\django\db\models\query.py", line 1270, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\install\Projects_1\env\lib\site-packages\django\db\models\sql\compiler.py", line 1416, in execute_sql
cursor.execute(sql, params)
File "C:\install\Projects_1\env\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\install\Projects_1\env\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:\install\Projects_1\env\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\install\Projects_1\env\lib\site-packages\django\db\backends\utils.py", line 79, in _execute
with self.db.wrap_database_errors:
File "C:\install\Projects_1\env\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\install\Projects_1\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\install\Projects_1\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
Exception Type: OperationalError at /admin/meetups/meetup/add/
Exception Value: table meetups_meetup has no column named enormus
Errors, when I input: makemigration and migrate
(env) PS C:\install\Projects_1> python manage.py makemigrations
System check identified some issues:
WARNINGS:
meetups.Meetup.participant: (fields.W340) null has no effect on ManyToManyField.
You are trying to add a non-nullable field 'dates' to meetup without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option: 1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
>>> '2021-10-10'
You are trying to add a non-nullable field 'organizer_emails' to meetup without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option: 1
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
>>> test#.test.com
Invalid input: invalid syntax (<string>, line 1)
>>> 'test#.test.com'
Migrations for 'meetups':
meetups\migrations\0011_auto_20211026_2116.py
- Remove field enormus from meetup
- Add field dates to meetup
- Add field organizer_emails to meetup
(env) PS C:\install\Projects_1> python manage.py migrate
System check identified some issues:
WARNINGS:
meetups.Meetup.participant: (fields.W340) null has no effect on ManyToManyField.
Operations to perform:
Apply all migrations: admin, auth, contenttypes, meetups, sessions
Running migrations:
Applying meetups.0005_auto_20211026_1234...Traceback (most recent call last):
File "C:\install\Projects_1\manage.py", line 22, in <module>
main()
File "C:\install\Projects_1\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\install\Projects_1\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\install\Projects_1\env\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\install\Projects_1\env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\install\Projects_1\env\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\install\Projects_1\env\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "C:\install\Projects_1\env\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle
post_migrate_state = executor.migrate(
File "C:\install\Projects_1\env\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "C:\install\Projects_1\env\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "C:\install\Projects_1\env\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\install\Projects_1\env\lib\site-packages\django\db\migrations\migration.py", line 126, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\install\Projects_1\env\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards
schema_editor.add_field(
File "C:\install\Projects_1\env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 330, in add_field
self._remake_table(model, create_field=field)
File "C:\install\Projects_1\env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 191, in _remake_table
self.effective_default(create_field)
File "C:\install\Projects_1\env\lib\site-packages\django\db\backends\base\schema.py", line 324, in effective_default
return field.get_db_prep_save(self._effective_default(field), self.connection)
File "C:\install\Projects_1\env\lib\site-packages\django\db\models\fields\__init__.py", line 842, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "C:\install\Projects_1\env\lib\site-packages\django\db\models\fields\__init__.py", line 1271, in get_db_prep_value
value = self.get_prep_value(value)
File "C:\install\Projects_1\env\lib\site-packages\django\db\models\fields\__init__.py", line 1266, in get_prep_value
return self.to_python(value)
File "C:\install\Projects_1\env\lib\site-packages\django\db\models\fields\__init__.py", line 1228, in to_python
parsed = parse_date(value)
File "C:\install\Projects_1\env\lib\site-packages\django\utils\dateparse.py", line 75, in parse_date
match = date_re.match(value)
TypeError: expected string or bytes-like object

How i can acces to another class, while i'm enter the information for the first class from shell?

I'm trying to fill write the models from shell and i was trying to fill the information for input has ( ForeignKey ) that make it access to another class.
that is my code in pycharm :
class Team(models.Model):
name = models.CharField(max_length=256, unique=True)
details = models.TextField()
def __str__(self):
return self.name
class Player(models.Model):
name = models.CharField(max_length=256)
number = models.IntegerField()
age = models.IntegerField()
position_in_field = models.CharField(max_length=256, choices=(('1', 'حارس'), ('2', 'دفاع'), ('3', 'وسط'), ('4', 'هجوم')))
is_captain = models.BooleanField(default=False)
team = models.ForeignKey(Team)
def __str__(self):
return '{} - {}'.format(self.name, self.team)
and this is the result:
python manage.py shell
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 22:20:52) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from teams.models import Player
>>> from teams.models import Team
>>> Player.objects.create(name='محمد إبراهيم', number='25', age='27', position_in_field='هجوم', is_captain=False, team='فريق الزمالك')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "D:\cj\projects\django\teammanager_env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "D:\cj\projects\django\teammanager_env\lib\site-packages\django\db\models\query.py", line 392, in create
obj = self.model(**kwargs)
File "D:\cj\projects\django\teammanager_env\lib\site-packages\django\db\models\base.py", line 555, in __init__
_setattr(self, field.name, rel_obj)
File "D:\cj\projects\django\teammanager_env\lib\site-packages\django\db\models\fields\related_descriptors.py", line 216, in __set__
self.field.remote_field.model._meta.object_name,
ValueError: Cannot assign "'فريق الزمالك'": "Player.team" must be a "Team" instance.
When you create a record with a foreign key, you have to indicate the record in the referenced model through its primary key.
In the case of model Team, you didn't set a primary key explicitly, so Djangosets de default field mode_id, that is a autoincremental PositiveIntegerField, that is what you have to indicate in the referencing record.
Player.objects.create(name='محمد إبراهيم', number='25', age='27', position_in_field='هجوم', is_captain=False, team_id=1)
If you have a model object with the referenced team, you can use it too:
Player.objects.create(name='محمد إبراهيم', number='25', age='27', position_in_field='هجوم', is_captain=False, team=team_instance)

what am I missing to get this error : <Cart: 22> is not JSON serializable?

Good day,
I'm getting the following error: is not JSON serializable
but I'm not sure why am I getting it. Everything was working fine until I decided to start making use of sessions to fire up my user cart adding and removal of items
This is my view:
def add_or_update_cart(request, slug):
request.session.set_expiry(180)
new_total = 0.00
try:
# check that session exists
the_cart_id = request.session['cart_id']
except:
new_cart_id = Cart()
new_cart_id.save()
request.session['cart_id'] = new_cart_id
the_cart_id = new_cart_id.id
cart = Cart.objects.get(id=the_cart_id)
try:
product = Product.objects.get(slug=slug)
except Product.DoesNotExist:
pass
except:
pass
if not product in cart.products.all():
cart.products.add(product)
else:
cart.products.remove(product)
for item in cart.products.all():
new_total += float(item.price)
request.session['items_total'] = cart.products.count()
cart.total = new_total
cart.save()
print(cart.products.count())
return HttpResponseRedirect(reverse('cart:cart'))
Models:
class Cart(models.Model):
products = models.ManyToManyField(Product, null=True, blank=True)
total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
cart_status = models.BooleanField(default=False)
def __str__(self):
return '%s' % self.id
def item_name(self):
return " ".join([str(p) for p in self.product.all()])
and in my template:
<li role="presentation">Cart <span class="badge">{{ request.session.items_total }}</span></li>
The traceback:
Internal Server Error: /my-cart/puma/
Traceback (most recent call last):
File "/home/drcongo/.virtualenvs/eCommerce/lib/python3.4/site-packages/django/core/handlers/base.py", line 235, in get_response
response = middleware_method(request, response)
File "/home/drcongo/.virtualenvs/eCommerce/lib/python3.4/site-packages/django/contrib/sessions/middleware.py", line 50, in process_response
request.session.save()
File "/home/drcongo/.virtualenvs/eCommerce/lib/python3.4/site-packages/django/contrib/sessions/backends/db.py", line 82, in save
obj = self.create_model_instance(data)
File "/home/drcongo/.virtualenvs/eCommerce/lib/python3.4/site-packages/django/contrib/sessions/backends/db.py", line 68, in create_model_instance
session_data=self.encode(data),
File "/home/drcongo/.virtualenvs/eCommerce/lib/python3.4/site-packages/django/contrib/sessions/backends/base.py", line 88, in encode
serialized = self.serializer().dumps(session_dict)
File "/home/drcongo/.virtualenvs/eCommerce/lib/python3.4/site-packages/django/core/signing.py", line 95, in dumps
return json.dumps(obj, separators=(',', ':')).encode('latin-1')
File "/usr/lib/python3.4/json/__init__.py", line 237, in dumps
**kw).encode(obj)
File "/usr/lib/python3.4/json/encoder.py", line 192, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.4/json/encoder.py", line 250, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python3.4/json/encoder.py", line 173, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <Cart: 31> is not JSON serializable
I will appreciate any help on this.
The error arises when Django tries to serialize a model instance here
request.session['cart_id'] = new_cart_id
new_cart_id is a model instance and cannot be serialized.
It seems you wanted to assign the primary key of the instance to the key cart_id.
request.session['cart_id'] = new_cart_id.id

Update with Tastypie in Resource with Foreign Keys

I have a problem (unsupported operand type(s) for ** or pow(): 'Decimal' and 'NoneType') with resources involved in foreign key constrains. Here is a piece of code (a contacts belongs to a department and to a client):
class Client(models.Model):
name = models.CharField(max_length=100, unique=True)
address = models.CharField(max_length=100, null=True)
class Department(models.Model):
name = models.CharField(max_length=50, unique=True)
class Contact(models.Model):
name = models.CharField(max_length=50, null=True)
phone = models.CharField(max_length=20, null=True)
email = models.EmailField(max_length=50, null=True)
department = models.ForeignKey(Department)
client = models.ForeignKey(Client)
class BaseResource(ModelResource):
class Meta:
allowed_methods = ['get','post', 'put', 'delete', 'patch']
authorization = Authorization()
abstract = True
class ClientResource(BaseResource):
class Meta(BaseResource.Meta):
queryset = Client.objects.all()
resource_name = 'client'
class DepartmentResource(BaseResource):
class Meta(BaseResource.Meta):
queryset = Department.objects.all()
resource_name = 'department'
class ContactResource(BaseResource):
department = fields.ToOneField(DepartmentResource, 'department', full=True)
client = fields.ToOneField(ClientResource, 'client', full=False)
class Meta(BaseResource.Meta):
queryset = Contact.objects.all()
resource_name = 'contact'
When I try to update a department I haven't got any problem. I do that with:
curl -v -XPATCH -H "Content-Type:application/json" -d "{\"name\": \"Sales\"}" "http://localhost:8000/api/v1/department/1/"
But when I try to do the same in the other resources
curl -v -X PATCH -H "Content-Type:application/json" -d "{\"name\": \"XYZ\"}" "http://localhost:8000/api/v1/client/1/"
returns the following error:
"error_message": "unsupported operand type(s) for ** or pow(): 'Decimal' and NoneType'"
"traceback": "Traceback (most recent call last):
File \"C:\\Python27\\lib\\site-packages\\tastypie\\resources.py\", line 192, in wrapper\n response = callback(request, *args, **kwargs)
File \"C:\\Python27\\lib\\site-packages\\tastypie\\resources.py\", line 406, in dispatch_detail\n return self.dispatch('detail', request, **kwargs)
File \"C:\\Python27\\lib\\site-packages\\tastypie\\resources.py\", line 427, in dispatch\n response = method(request, **kwargs)
File \"C:\\Python27\\lib\\site-packages\\tastypie\\resources.py\", line 1332, in patch_detail\n self.update_in_place(request, bundle, deserialized)
File \"C:\\Python27\\lib\\site-packages\\tastypie\\resources.py\", line 1346, in update_in_place\n return self.obj_update(original_bundle, request=request, pk=original_bundle.obj.pk)
File \"C:\\Python27\\lib\\site-packages\\tastypie\\resources.py\", line 1824, in obj_update\n bundle.obj.save()
File \"C:\\Python27\\lib\\site-packages\\django\\db\\models\\base.py\", line 463, in save\n self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File \"C:\\Python27\\lib\\site-packages\\django\\db\\models\\base.py\", line 529, in save_base\n rows = manager.using(using).filter(pk=pk_val)._update(values)
File \"C:\\Python27\\lib\\site-packages\\django\\db\\models\\query.py\", line 557, in _update\n return query.get_compiler(self.db).execute_sql(None)
File \"C:\\Python27\\lib\\site-packages\\django\\db\\models\\sql\\compiler.py\", line 986, in execute_sql\n cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File \"C:\\Python27\\lib\\site-packages\\django\\db\\models\\sql\\compiler.py\", line 808, in execute_sql\n sql, params = self.as_sql()
File \"C:\\Python27\\lib\\site-packages\\django\\db\\models\\sql\\compiler.py\", line 951, in as_sql\n val = field.get_db_prep_save(val, connection=self.connection)
File \"C:\\Python27\\lib\\site-packages\\django\\db\\models\\fields\\__init__.py\", line 874, in get_db_prep_save\n self.max_digits, self.decimal_places)
File \"C:\\Python27\\lib\\site-packages\\django\\db\\backends\\__init__.py\", line 809, in value_to_db_decimal\n return util.format_number(value, max_digits, decimal_places)
File \"C:\\Python27\\lib\\site-packages\\django\\db\\backends\\util.py\", line 149, in format_number\n return u'%s' % str(value.quantize(decimal.Decimal(\".1\") ** decimal_places, context=context))
TypeError: unsupported operand type(s) for ** or pow(): 'Decimal' and 'NoneType'\n"}* Closing connection #0
and
curl -v -X PATCH -H "Content-Type:application/json" -d "{\"name\": \"ZZZZ\"}" "http://localhost:8000/api/v1/contact/1/"
returns
The 'department' field has was given data that was not a URI, not a dictionary-alike and does not have a 'pk' attribute: <Bundle for obj: 'Department object' and with data: '{'id': u'1', 'name': u'Sales', 'resource_uri': '/api/v1/department/1/'}'>.* Closing connection #0
I suppose something is wrong in my foreign keys definition but I don't know what. When I do GET operations everything is OK. What is wrong in my definition? Thank you very much.

Problem with Django-dbindexer

I asked my question in appropriate Google Group (http://groups.google.com/group/django-non-relational/browse_thread/thread/a51c1903af175e1c), but developers seems are kinda busy now, so I'm afraid my question will remain unanswered. Hope I'll find solution of my problem here.
Essense is:
I use Django-nonrel + GAE + Blog App from Django Basic apps
From admin panel of my app I tried to create new blog post. And got the following exception:
DatabaseError: Lookup type 'month' isn't supported
I asked about this in related google group and was answered to use django-dbindexer.
Regarding it desription it is exactly what I need, so I guided through all instructions and "attached" it to my app. Indexing is done, but I however get the same exception. Here is the full trace:
Traceback (most recent call last):
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\core\handlers\base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\contrib\admin\options.py", line 308, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\utils\decorators.py", line 93, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\views\decorators\cache.py", line 79, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\contrib\admin\sites.py", line 190, in inner
return view(request, *args, **kwargs)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\utils\decorators.py", line 28, in _wrapper
return bound_func(*args, **kwargs)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\utils\decorators.py", line 93, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\utils\decorators.py", line 24, in bound_func
return func(self, *args2, **kwargs2)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\db\transaction.py", line 282, in inner
res = func(*args, **kwargs)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\contrib\admin\options.py", line 852, in add_view
if form.is_valid():
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\forms\forms.py", line 121, in is_valid
return self.is_bound and not bool(self.errors)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\forms\forms.py", line 112, in _get_errors
self.full_clean()
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\forms\forms.py", line 269, in full_clean
self._post_clean()
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\forms\models.py", line 338, in _post_clean
self.validate_unique()
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\forms\models.py", line 347, in validate_unique
self.instance.validate_unique(exclude=exclude)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\db\models\base.py", line 669, in validate_unique
date_errors = self._perform_date_checks(date_checks)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\db\models\base.py", line 791, in _perform_date_checks
if qs.exists():
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\db\models\query.py", line 498, in exists
return self.query.has_results(using=self.db)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\django\db\models\sql\query.py", line 428, in has_results
return compiler.has_results()
File "F:\Its_mine19\Programming\Java\pineapplemon\src\djangotoolbox\db\basecompiler.py", line 222, in has_results
return self.get_count(check_exists=True)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\djangotoolbox\db\basecompiler.py", line 269, in get_count
return self.build_query().count(high_mark)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\djangotoolbox\db\basecompiler.py", line 275, in build_query
query.add_filters(self.query.where)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\djangotoolbox\db\basecompiler.py", line 72, in add_filters
self.add_filters(child)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\djangotoolbox\db\basecompiler.py", line 76, in add_filters
self.add_filter(column, lookup_type, self._negated, db_type, value)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\djangoappengine\db\compiler.py", line 57, in _func
return func(*args, **kwargs)
File "F:\Its_mine19\Programming\Java\pineapplemon\src\djangoappengine\db\compiler.py", line 211, in add_filter
raise DatabaseError("Lookup type %r isn't supported" % lookup_type)
DatabaseError: Lookup type 'month' isn't supported
Here is my data model (from basic.blog.models):
class Post(models.Model):
"""Post model."""
STATUS_CHOICES = (
(1, _('Draft')),
(2, _('Public')),
)
title = models.CharField(_('title'), max_length=200)
slug = models.SlugField(_('slug'), unique_for_date='publish')
author = models.ForeignKey(User, blank=True, null=True)
body = models.TextField(_('body'), )
tease = models.TextField(_('tease'), blank=True, help_text=_('Concise text suggested. Does not appear in RSS feed.'))
status = models.IntegerField(_('status'), choices=STATUS_CHOICES, default=2)
allow_comments = models.BooleanField(_('allow comments'), default=True)
publish = models.DateTimeField(_('publish'), default=datetime.datetime.now)
created = models.DateTimeField(_('created'), auto_now_add=True)
modified = models.DateTimeField(_('modified'), auto_now=True)
categories = models.ManyToManyField(Category, blank=True)
tags = TagField()
objects = PublicManager()
class Meta:
verbose_name = _('post')
verbose_name_plural = _('posts')
db_table = 'blog_posts'
ordering = ('-publish',)
get_latest_by = 'publish'
def __unicode__(self):
return u'%s' % self.title
#permalink
def get_absolute_url(self):
return ('blog_detail', None, {
'year': self.publish.year,
'month': self.publish.strftime('%b').lower(),
'day': self.publish.day,
'slug': self.slug
})
def get_previous_post(self):
return self.get_previous_by_publish(status__gte=2)
def get_next_post(self):
return self.get_next_by_publish(status__gte=2)
Here is what I have in dbindexes module of my app (basic.blog.dbindexes):
from basic.blog.models import Post
from dbindexer.api import register_index
register_index(Post, {
'publish': 'month',
# 'created': 'month',
# 'modified': 'month',
})
import logging
logger = logging.getLogger(__name__)
logger.info('Basic.blog dbindexes') # Logging statement to check if this module is ever executed to be sure indexing is done
Thanks in advance for any help.

Resources