Django Model with custom string id field not being deleted - django

I have a model with a custom string for an id.
class BaseModel(Model):
id = CharField(
max_length=23,
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
default=generate,
editable=False,
)
When deleting, I am getting this error.
Internal Server Error: /admin/sampleapp/user/
Traceback (most recent call last):
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1988, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'AC7EEKrEhYZ9p1r-Q'
The above exception was the direct cause of the following exception:
response = func(self, request, queryset)
File "path\to\sampleapp\venv\lib\site-packages\django\contrib\admin\actions.py", line 39, in delete_selected
) = modeladmin.get_deleted_objects(queryset, request)
File "path\to\sampleapp\venv\lib\site-packages\django\contrib\admin\options.py", line 2099, in get_deleted_objects
return get_deleted_objects(objs, request, self.admin_site)
File "path\to\sampleapp\venv\lib\site-packages\django\contrib\admin\utils.py", line 120, in get_deleted_objects
collector.collect(objs)
File "path\to\sampleapp\venv\lib\site-packages\django\contrib\admin\utils.py", line 186, in collect
return super().collect(objs, source_attr=source_attr, **kwargs)
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\deletion.py", line 343, in collect
field.remote_field.on_delete(self, field, sub_objs, self.using)
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\deletion.py", line 23, in CASCADE
collector.collect(
File "path\to\sampleapp\venv\lib\site-packages\django\contrib\admin\utils.py", line 186, in collect
return super().collect(objs, source_attr=source_attr, **kwargs)
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\deletion.py", line 365, in collect
sub_objs = field.bulk_related_objects(new_objs, self.using)
File "path\to\sampleapp\venv\lib\site-packages\django\contrib\contenttypes\fields.py", line 524, in bulk_related_objects
return self.remote_field.model._base_manager.db_manager(using).filter(
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\query.py", line 1071, in filter
return self._filter_or_exclude(False, args, kwargs)
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\query.py", line 1089, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, args, kwargs)
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\query.py", line 1096, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\sql\query.py", line 1502, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\sql\query.py", line 1532, in _add_q
child_clause, needed_inner = self.build_filter(
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\sql\query.py", line 1448, in build_filter
condition = self.build_lookup(lookups, col, value)
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\sql\query.py", line 1273, in build_lookup
lookup = lookup_class(lhs, rhs)
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\lookups.py", line 27, in __init__
self.rhs = self.get_prep_lookup()
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\lookups.py", line 276, in get_prep_lookup
rhs_value = self.lhs.output_field.get_prep_value(rhs_value)
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1990, in get_prep_value
raise e.__class__(
ValueError: Field 'object_pk' expected a number but got 'AC7EEKrEhYZ9p1r-Q'.
"POST /admin/sampleapp/user/ HTTP/1.1" 500 213503
Kindly help in solving this issue.
I first noticed this issue when attempting to delete via admin but that didn't work. Upon inspection, I noticed the issue was that the model could not be deleted even via shell.

From your traceback:
ValueError: invalid literal for int() with base 10: 'AC7EEKrEhYZ9p1r-Q'
It's expecting an integer.
Is there a particular reason you want to replace the id field? You could always just create a separate field for your custom one and use that as the id elsewhere in your program

Related

Django rest framework Serializer Save() problem

Hi there i am new ot django and django rest framework and i am having torouble when using serializers with PrimarayKeyTelatedFields() the code below is my code for my models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=50)
age = models.IntegerField(default=0)
class Book(models.Model):
name = models.CharField(max_length=40)
author = models.ForeignKey(to=Author, on_delete=models.CASCADE)
below is my serializer code
from rest_framework import serializers
from books.models import Book, Author
class BookSerializer(serializers.ModelSerializer):
author_id = serializers.PrimaryKeyRelatedField(many=False,
queryset=Author.objects.all())
class Meta:
model = Book
fields = ['id', 'name', 'author_id']
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = Author
fields = ['id', 'name', 'age']
and when i try to execute following commands in shell
>>from books.api.serializers import BookSerializer, AuthorSerializer
>> play1 = BookSerializer(data = { 'author_id':1 ,'name':'book1' })
>>play1.is_valid()
True
>>play1.save()
After executing above i got the huge error as i pasted below
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1988, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'Author'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\serializers.py", line 962, in create
instance = ModelClass._default_manager.create(**validated_data)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 514, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 806, in save
self.save_base(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 857, in save_base
updated = self._save_table(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 1000, in _save_table
results = self._do_insert(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 1041, in _do_insert
return manager._insert(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\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\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1620, in execute_sql
for sql, params in self.as_sql():
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1547, in as_sql
value_rows = [
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1548, in <listcomp>
[
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1549, in <listcomp>
self.prepare_value(field, self.pre_save_val(field, obj))
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1487, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related.py", line 1126, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 910, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 2668, in get_db_prep_value
value = self.get_prep_value(value)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1990, in get_prep_value
raise e.__class__(
TypeError: Field 'id' expected a number but got <Author: Author object (1)>.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\serializers.py", line 212, in save
self.instance = self.create(validated_data)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\serializers.py", line 981, in create
raise TypeError(msg)
TypeError: Got a `TypeError` when calling `Book.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Book.objects.create()`. You may need to make the field read-only, or override the BookSerializer.create() method to handle this correctly.
Original exception was:
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1988, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'Author'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\serializers.py", line 962, in create
instance = ModelClass._default_manager.create(**validated_data)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 514, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 806, in save
self.save_base(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 857, in save_base
updated = self._save_table(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 1000, in _save_table
results = self._do_insert(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 1041, in _do_insert
return manager._insert(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\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\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1620, in execute_sql
for sql, params in self.as_sql():
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1547, in as_sql
value_rows = [
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1548, in <listcomp>
[
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1549, in <listcomp>
self.prepare_value(field, self.pre_save_val(field, obj))
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1487, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related.py", line 1126, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 910, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 2668, in get_db_prep_value
value = self.get_prep_value(value)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1990, in get_prep_value
raise e.__class__(
TypeError: Field 'id' expected a number but got <Author: Author object (1)>.
you passed here an object instead of id..
author_id = serializers.PrimaryKeyRelatedField(many=False,
queryset=Author.objects.all())
you should pass an id like this
author_id = serializers.PrimaryKeyRelatedField(many=False,
queryset=Author.objects.get(id=request.user.id))
Remember whatever you queried it should be an int value not str or object
Cause
The problem is caused by setting author_id with serializer.PrimaryKeyRelatedField
Explanation
Django will internally auto-create an attribute for related fields (ForeignKey, OneToOneField, ...) with the suffix _id appending to the declared field name. The data type of this field is a number. In this case, the author field in Book will have an attribute called author_id. The problem comes from serializer.PrimaryKeyRelatedField returning a model instance in the serializer's validated data, causing field author_id to be set with Author instance. Resulting in an error.
Solution
Rename author_id attribute to author.
class BookSerializer(serializers.ModelSerializer):
author = serializers.PrimaryKeyRelatedField(queryset=Author.objects.all())
class Meta:
model = Book
fields = ['id', 'name', 'author']

I am trying to get data from database using python Django but got an error

Hello everyone I am trying to get data from database but it give me error in case when I am trying to get single data from db as shown below
wahid = Webapp.objects.get(title="Ecommerce Website")
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 418, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 942, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, *args, **kwargs)
File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1258, in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1084, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1481, in names_to_path
raise FieldError("Cannot resolve keyword '%s' into field. "
django.core.exceptions.FieldError: Cannot resolve keyword 'title' into field. Choices are: created, demo_link, description, id, review, source_link, tags, tiltle, vote_ratio, vote_total
It will work only on getting all data from db as shown in image
There is a spelling mistake,
You have created field name "tiltle" in models, however you are trying to fetch "title" in your get query
Also, using get query might throw an error if there are more than one record that have title="Ecommerce Website"
for that you can use
Webapp.objects.filter(title="Ecommerce Website")
you should rename title field in your model, it seems you enter title field name to wrong dictation
'tiltle' must be 'title' in your model

ValidationError - Django Q Query - is not a valid UUID

I am trying to get a value from the User Model, my requirement is that or condition should be in same query.
User.objects.get(
Q(premium_referral=form.cleaned_data.get('referral_code')) |
Q(id=form.cleaned_data.get('referral_code'))
)
But it gives an error:
ValidationError at /register
['“XUSB5” is not a valid UUID.']
The above query works perfect for id but not for premium_referral field. If I pass a UUID, it works, but if I pass 5 char premium_referral, then it fails.
Query also works perfectly when I separate them:
User.objects.get(premium_referral=form.cleaned_data.get('referral_code'))
User.objects.get(id=form.cleaned_data.get('referral_code'))
Below is the model:
class User(AbstractBaseUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
premium_referral = models.CharField(('Premium Referral Code'), max_length=30, null=True, blank=True, unique=True)
Traceback
Internal Server Error: /register
Traceback (most recent call last):
File "env/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2434, in to_python
return uuid.UUID(**{input_form: value})
File "/usr/lib/python3.8/uuid.py", line 171, in __init__
raise ValueError('badly formed hexadecimal UUID string')
ValueError: badly formed hexadecimal UUID string
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "apps/accounts/views.py", line 31, in register
referrer = User.objects.get(
File "env/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "env/lib/python3.8/site-packages/django/db/models/query.py", line 424, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File "env/lib/python3.8/site-packages/django/db/models/query.py", line 941, in filter
return self._filter_or_exclude(False, args, kwargs)
File "env/lib/python3.8/site-packages/django/db/models/query.py", line 961, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, args, kwargs)
File "env/lib/python3.8/site-packages/django/db/models/query.py", line 968, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1393, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1412, in _add_q
child_clause, needed_inner = self.build_filter(
File "env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1265, in build_filter
return self._add_q(
File "env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1412, in _add_q
child_clause, needed_inner = self.build_filter(
File "env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1347, in build_filter
condition = self.build_lookup(lookups, col, value)
File "env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1193, in build_lookup
lookup = lookup_class(lhs, rhs)
File "env/lib/python3.8/site-packages/django/db/models/lookups.py", line 25, in __init__
self.rhs = self.get_prep_lookup()
File "env/lib/python3.8/site-packages/django/db/models/lookups.py", line 77, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "env/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2418, in get_prep_value
return self.to_python(value)
File "env/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2436, in to_python
raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['“XUSB5” is not a valid UUID.']
[19/Nov/2021 09:52:54] "POST /register HTTP/1.1" 500 154403
The reason this happens is because the id (or the premium_referral) is a UUIDField [Django-doc]. It thus does not make much sense to pass XUSB5 as code, since that is an invalid UUID).
What you can do is check if it can be converted to a UUID and thus filter with:
from uuid import UUID
query = form.cleaned_data.get('referral_code')
qobj = Q(premium_referral=query)
try:
qobj |= Q(id=UUID(query))
except ValueError:
pass
User.objects.get(
qobj
)

django celery asynchronous file saves to storage

So I want to asynchronously conduct file saves to django file storage. I've tried to achieve this by overwriting the default File System Storage class.
import hashlib
import os
import uuid
import django.core.files.storage as storage
from celery import shared_task
from django.core.files import File
class DefaultStorage(storage.FileSystemStorage):
def __init__(self):
super(DefaultStorage, self).__init__()
#shared_task
def _save(self, name, content):
# need to encrypt file before saving
return super(DefaultStorage, self)._save(name, content)
#shared_task
def _open(self, name, mode='rb'):
# need to decrypt before opening
return File(open(self.path(name), mode))
def get_available_name(self, name, max_length=None):
# we return a hash of the file given,
# in case we miss out on uniqueness, django calls
# the get_alternative_name method
dir_name, file_name = os.path.split(name)
file_root, file_ext = os.path.splitext(file_name)
file_root = hashlib.md5(file_root.encode()).hexdigest()
name = os.path.join(dir_name, file_root + file_ext)
return super(DefaultStorage, self).get_available_name(name, max_length)
def get_alternative_name(self, file_root, file_ext):
# we insert a random uuid hex string into the given
# file name before returning the same back
return '%s%s%s' % (file_root, uuid.uuid4().hex, file_ext)
def save(self, name, content, max_length=None):
# override existing system storage save method
# to ensure that we call the shared task and
# utilize the distributed task queue celery offers
has_chunks = hasattr(content, 'chunks')
name = content.name if not name else name
content = File(content, name) if not has_chunks else content
name = self.get_available_name(name, max_length=max_length)
saved = self._save.delay(self, name, content)
return saved
def open(self, name, mode='rb'):
# override existing system storage open method
# to ensure that we call the shared task and
# utilize the distributed task queue celery offers
return self._open.delay(name, mode)
The idea is to override the existing save method to fire off the shared_task named _save. However, I am facing the following error while trying to do the same.
Traceback (most recent call last):
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\iyapp\PycharmProjects\cloud-server\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\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\rest_framework\generics.py", line 242, in post
return self.create(request, *args, **kwargs)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\rest_framework\mixins.py", line 19, in create
self.perform_create(serializer)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\rest_framework\mixins.py", line 24, in perform_create
serializer.save()
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\rest_framework\serializers.py", line 205, in save
self.instance = self.create(validated_data)
File "C:\Users\iyapp\PycharmProjects\cloud-server\api_backend\serializers\partial.py", line 32, in create
return super(PartialUploadSerializer, self).create(validated_data)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\rest_framework\serializers.py", line 939, in create
instance = ModelClass._default_manager.create(**validated_data)
File "C:\Users\iyapp\PycharmProjects\cloud-server\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\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\query.py", line 447, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\iyapp\PycharmProjects\cloud-server\api_backend\models\uploads.py", line 30, in save
super(Upload, self).save(*args, **kwargs)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\base.py", line 754, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\base.py", line 792, in save_base
force_update, using, update_fields,
File "C:\Users\iyapp\PycharmProjects\cloud-server\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\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\base.py", line 935, in _do_insert
using=using, raw=raw,
File "C:\Users\iyapp\PycharmProjects\cloud-server\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\iyapp\PycharmProjects\cloud-server\venv\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\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1396, in execute_sql
for sql, params in self.as_sql():
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1341, in as_sql
for obj in self.query.objs
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1341, in <listcomp>
for obj in self.query.objs
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1340, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1291, in pre_save_val
return field.pre_save(obj, add=True)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\fields\files.py", line 307, in pre_save
file.save(file.name, file.file, save=False)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\django\db\models\fields\files.py", line 87, in save
self.name = self.storage.save(name, content, max_length=self.field.max_length)
File "C:\Users\iyapp\PycharmProjects\cloud-server\api_backend\models\storage\default_storage.py", line 48, in save
saved = self._save.delay(self, name, content)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\celery\app\task.py", line 421, in delay
return self.apply_async(args, kwargs)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\celery\app\task.py", line 565, in apply_async
**options
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\celery\app\base.py", line 749, in send_task
amqp.send_task_message(P, name, message, **options)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\celery\app\amqp.py", line 532, in send_task_message
**properties
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\kombu\messaging.py", line 166, in publish
compression, headers)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\kombu\messaging.py", line 249, in _prepare
body) = dumps(body, serializer=serializer)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\kombu\serialization.py", line 220, in dumps
payload = encoder(data)
File "C:\Users\iyapp\AppData\Local\Programs\Python\Python36-32\lib\contextlib.py", line 99, in __exit__
self.gen.throw(type, value, traceback)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\kombu\serialization.py", line 53, in _reraise_errors
reraise(wrapper, wrapper(exc), sys.exc_info()[2])
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\kombu\exceptions.py", line 21, in reraise
raise value.with_traceback(tb)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\kombu\serialization.py", line 49, in _reraise_errors
yield
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\kombu\serialization.py", line 220, in dumps
payload = encoder(data)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\kombu\utils\json.py", line 66, in dumps
**dict(default_kwargs, **kwargs))
File "C:\Users\iyapp\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Users\iyapp\AppData\Local\Programs\Python\Python36-32\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\iyapp\AppData\Local\Programs\Python\Python36-32\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\iyapp\PycharmProjects\cloud-server\venv\lib\site-packages\kombu\utils\json.py", line 55, in default
return super().default(o)
File "C:\Users\iyapp\AppData\Local\Programs\Python\Python36-32\lib\json\encoder.py", line 180, in default
o.__class__.__name__)
kombu.exceptions.EncodeError: Object of type 'DefaultStorage' is not JSON serializable
I believe I have found the source of the issue. It is because we cannot pass "file" objects as parameters to shared_task functions. If this is the case, then how can I send my file to the _save function?
Before sending, the file isn't saved yet. We need to save the file only after receiving.

Query inherited models

I have 3 Models:
Actor(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
type = models.Charfield(max_length=20)
Organisation(Actor):
name = models.Charfield(max_length=20)
actor = models.OneToOneField(Actor, on_delete=Models.CASCADE)
parent_organisation = models.ForeignKey(Actor, on_delete=models.CASCADE)
CustomUser(AbstractBaseUser,PermissionsMixin,Actor):
name = models.Charfield(max_length=20)
member_of = models.ManyToManyField(Actor, on_delete=models.CASCADE)
I am basically trying to get all users within an organisation:
User and Organisation share a common named id - Actor and Inherit from this class.
I have tried:
user_list = CustomerUser.objects.filter(parent__parent__id=request.session['organisation']
and
user_list = Organisation.objects.filter(parent__parent_user_organisation=request.session[''organisation']
and
user_list = Actor.objects.filter(parent__parent__user_organisation__in=request.session['organisation'])
although I would like to try and keep all queries on the actor model if possible. Eventually, id like to get all users within a multi-tiered organisation structure although for now, I'm happy to get just users based on Organisation_parent rather than ----- Organisation_parent_Organisation_parent etc...
I have changed my model structure to inherited to try and make queries easier but not having much luck.
The full trace:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-
packages/django/db/models/fields/__init__.py", line 2348, in to_python
return uuid.UUID(**{input_form: value})
File "/usr/local/lib/python3.8/uuid.py", line 171, in __init__
raise ValueError('badly formed hexadecimal UUID string')
During handling of the above exception (badly formed hexadecimal UUID string), another exception occurred: File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/src/app/administration/views.py", line 133, in user_list
user_list = Actor.objects.filter(parent__parent__user_organisation__in=request.session['organisation']) File "/usr/local/lib/python3.8/site-packages/django/db/models/manager.py", line 82, 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 904, in filter
return self._filter_or_exclude(False, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 923, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs)) File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1350, in add_q
clause, _ = self._add_q(q_object, self.used_aliases) File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter( File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1311, in build_filter
condition = self.build_lookup(lookups, col, value) File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1165, in build_lookup
lookup = lookup_class(lhs, rhs) File "/usr/local/lib/python3.8/site-packages/django/db/models/lookups.py", line 22, in __init__
self.rhs = self.get_prep_lookup() File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/related_lookups.py", line 59, in get_prep_lookup
self.rhs = [target_field.get_prep_value(v) for v in self.rhs] File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/related_lookups.py", line 59, in <listcomp>
self.rhs = [target_field.get_prep_value(v) for v in self.rhs] File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/related.py", line 945, in get_prep_value
return self.target_field.get_prep_value(value) File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2332, in get_prep_value
return self.to_python(value) File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2350, in to_python
raise exceptions.ValidationError(
Exception Type: ValidationError at /administration/administration/user/list Exception Value: ['“4” is not a valid UUID.']