Hi guys i have this error when I'm trying to create or update the user model
the error is happening on the profile model
I'm using Django 2.1.7 with PostgreSQL
Internal Server Error: /accounts/update/
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\utils\dateparse.py", line 106, in parse_datetime
match = datetime_re.match(value)
TypeError: expected string or bytes-like object
Error Traceback
Internal Server Error: /accounts/update/
Traceback (most recent call last):
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\views\generic\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "E:\practice my skills\fullStackDjangoAndReact\chatapp\accounts\api.py", line 73, in post
user = user_ser.save()
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\rest_framework\serializers.py", line 207, in save
self.instance = self.update(self.instance, validated_data)
File "E:\practice my skills\fullStackDjangoAndReact\chatapp\accounts\serializers.py", line 67, in update
profile.save()
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\base.py", line 718, in save
force_update=force_update, update_fields=update_fields)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\base.py", line 748, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\base.py", line 812, in _save_table
forced_update)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\base.py", line 861, in _do_update
return filtered._update(values) > 0
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\query.py", line 712, in _update
return query.get_compiler(self.db).execute_sql(CURSOR)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\sql\compiler.py", line 1383, in execute_sql
cursor = super().execute_sql(result_type)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\sql\compiler.py", line 1052, in execute_sql
sql, params = self.as_sql()
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\sql\compiler.py", line 1349, in as_sql
val = field.get_db_prep_save(val, connection=self.connection)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\fields\__init__.py", line 790, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\fields\__init__.py", line 1429, in get_db_prep_value
value = self.get_prep_value(value)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\fields\__init__.py", line 1408, in get_prep_value
value = super().get_prep_value(value)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\fields\__init__.py", line 1268, in get_prep_value
return self.to_python(value)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\fields\__init__.py", line 1369, in to_python
parsed = parse_datetime(value)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\utils\dateparse.py", line 106, in parse_datetime
match = datetime_re.match(value)
TypeError: expected string or bytes-like object
the Profile Model:
class Profile(models.Model):
user = models.OneToOneField(User ,on_delete=models.CASCADE)
icon = models.CharField(max_length=256)
active = models.BooleanField(default=False)
join_date = models.DateTimeField(default=timezone.now, blank=True, null=True)
born_date = models.DateTimeField(blank=True, null=True)
The Serializer
class UpdateUserSer(serializers.ModelSerializer):
profile = UpdateProfileSer()
class Meta:
model = User
fields = ("username","email","first_name","profile")
def update(self , instance , validated_data):
prfile_data = validated_data.pop("profile")
instance.username = validated_data.get("username" , instance.username)
instance.email = validated_data.get("email" , instance.email)
instance.first_name = validated_data.get("first_name" , instance.first_name)
instance.save()
profile = instance.profile
profile.icon = prfile_data.get("icon" ,profile.icon)
profile.save()
return instance
def validate(self , data):
user_instance = self.context["request"].user
user_email = data["email"]
users = User.objects.all()
if users.filter(email = user_email).exclude(id=user_instance.id).exists():
raise serializers.ValidationError("this email has been token choose another one please")
return data
UpdateProfileSer
class UpdateProfileSer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ("icon",)
Related
I'm trying to create a structure where a list of books read is kept. I had set up a structure, but if the read finished statement is checked, it adds a new record. What I want to do is to create only 1 record according to that user and book id value and constantly update this record. When I want to do this, I get the following error, I cannot access the book id value. There are many similar questions, but I couldn't make the right application, I need suggestions.
Traceback (most recent call last):
File "E:\!Staj\bookorbooks\env\lib\site-packages\django\db\models\fields\__init__.py", line 1823, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'Book'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "E:\!Staj\bookorbooks\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "E:\!Staj\bookorbooks\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\!Staj\bookorbooks\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "E:\!Staj\bookorbooks\env\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "E:\!Staj\bookorbooks\env\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "E:\!Staj\bookorbooks\env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "E:\!Staj\bookorbooks\env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "E:\!Staj\bookorbooks\env\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "E:\!Staj\bookorbooks\env\lib\site-packages\rest_framework\generics.py", line 190, in post
return self.create(request, *args, **kwargs)
File "E:\!Staj\bookorbooks\env\lib\site-packages\rest_framework\mixins.py", line 19, in create
self.perform_create(serializer)
File "E:\!Staj\bookorbooks\bookorbooks\book\api\views\reading_history_views.py", line 32, in perform_create
obj_lst = ReadingHistory.objects.filter(book=book, child=child)
File "E:\!Staj\bookorbooks\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "E:\!Staj\bookorbooks\env\lib\site-packages\django\db\models\query.py", line 941, in filter
return self._filter_or_exclude(False, args, kwargs)
File "E:\!Staj\bookorbooks\env\lib\site-packages\django\db\models\query.py", line 961, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, args, kwargs)
File "E:\!Staj\bookorbooks\env\lib\site-packages\django\db\models\query.py", line 968, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "E:\!Staj\bookorbooks\env\lib\site-packages\django\db\models\sql\query.py", line 1393, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "E:\!Staj\bookorbooks\env\lib\site-packages\django\db\models\sql\query.py", line 1412, in _add_q
child_clause, needed_inner = self.build_filter(
File "E:\!Staj\bookorbooks\env\lib\site-packages\django\db\models\sql\query.py", line 1347, in build_filter
condition = self.build_lookup(lookups, col, value)
File "E:\!Staj\bookorbooks\env\lib\site-packages\django\db\models\sql\query.py", line 1193, in build_lookup
lookup = lookup_class(lhs, rhs)
File "E:\!Staj\bookorbooks\env\lib\site-packages\django\db\models\lookups.py", line 25, in __init__
self.rhs = self.get_prep_lookup()
File "E:\!Staj\bookorbooks\env\lib\site-packages\django\db\models\fields\related_lookups.py", line 117, in get_prep_lookup
self.rhs = target_field.get_prep_value(self.rhs)
File "E:\!Staj\bookorbooks\env\lib\site-packages\django\db\models\fields\__init__.py", line 1825, in get_prep_value
raise e.__class__(
TypeError: Field 'id' expected a number but got <Book: Example Book 1>.
Model
class ReadingHistory(AbstractBookBaseModel):
IS_FINISHED = ((False,
BookStrings.ReadingHistoryStrings.is_finished_false),
(True, BookStrings.ReadingHistoryStrings.is_finished_true))
book = models.ForeignKey(
"book.Book",
on_delete=models.CASCADE,
related_name="book_reading_history",
verbose_name=BookStrings.ReadingHistoryStrings.book_verbose_name)
child = models.ForeignKey(
"account.ChildProfile",
on_delete=models.CASCADE,
related_name="child_reading_history",
verbose_name=BookStrings.ReadingHistoryStrings.child_verbose_name)
is_finished = models.BooleanField(
choices=IS_FINISHED,
verbose_name=BookStrings.ReadingHistoryStrings.is_finished_verbose_name
)
class Meta:
verbose_name = BookStrings.ReadingHistoryStrings.meta_verbose_name
verbose_name_plural = BookStrings.ReadingHistoryStrings.meta_verbose_name_plural
def __str__(self):
return f"{self.child.user.first_name} {self.child.user.last_name} - \"{self.book.name}\" "
Serializer
class ReadingHistoryCreateSerializer(ModelSerializer):
class Meta:
model = ReadingHistory
exclude = ["child"]
# def create(self, validated_data):
# """
# If the user wants to add the same student to a class for the second time, it will throw an error.
# """
# created = self.Meta.model.objects.get(child = validated_data["child"], book = validated_data["book"])
# if not created:
# instance = self.Meta.model.objects.create(**validated_data)
# return instance
# else:
# is_finished_value = created.is_finished
# if is_finished_value == validated_data["is_finished"]:
# pass
# else:
# obj = self.Meta.model.objects.update(child = validated_data["child"], book = validated_data["book"], is_finished = validated_data["is_finished"])
# return obj
View
class AddReadingHistoryAPIView(CreateAPIView):
queryset = ReadingHistory.objects.all()
serializer_class = ReadingHistoryCreateSerializer
# def perform_create(self, serializer):
# return serializer.save(child=self.request.user.user_child)
def perform_create(self, serializer):
book = serializer.validated_data.get('book', ),
is_finished = serializer.validated_data.get('is_finished', )
child = self.request.user.user_child
obj_lst = ReadingHistory.objects.filter(book=int(book), child=child)
if obj_lst:
obj_lst.update(is_finished=is_finished)
else:
ReadingHistory.objects.create(book=book,
child=child,
is_finished=is_finished)
I am trying to implement bulk_create my inserting multiple objects in
a relation, not sure whether I am doing it right i have added trace back as well below is skill set model
class Skillset(models.Model):
skill_name = models.CharField(max_length=255)
def __str__(self):
return self.skill_name
my view
skill_name = request.POST.getlist('skill_name')
skill_level = request.POST.getlist('skill_level')
print(f'skill name-> {skill_name} skill level ->{skill_level}')
seeker_skll = []
# testing destructing
for skill_nme, skill_lvl in zip(skill_name, skill_level):
skill_set = Skillset.objects.get(skill_name=skill_nme)
seeker_skll.append(Seekerskillset(
skill_set=skill_set, skill_level=skill_lvl, seeker=user))
seeker_skll = Skillset.objects.bulk_create(seeker_skll)
print(seeker_skll)
return redirect('/users/dashboard')
Model
class Seekerskillset(models.Model):
skill_set = models.ForeignKey(Skillset, on_delete=models.CASCADE)
seeker = models.ForeignKey(SeekerProfile, on_delete=models.CASCADE)
skill_level = models.CharField(max_length=25)
class Meta:
verbose_name = 'Seeker skill set'
error i am getting
AttributeError: 'Seekerskillset' object has no attribute 'skill_name'
Traceback (most recent call last):
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\atif\PycharmProjects\my_proj\mysite_jobportal\seekerbuilder\views.py", line 43, in update_details
seeker_skll = Skillset.objects.bulk_create(seeker_skll)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 515, in bulk_create
objs_without_pk, fields, batch_size, ignore_conflicts=ignore_conflicts,
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 1293, in _batched_insert
self._insert(item, fields=fields, using=self.db, ignore_conflicts=ignore_conflicts)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\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\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1415, in execute_sql
for sql, params in self.as_sql():
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1360, in as_sql
for obj in self.query.objs
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1360, in <listcomp>
for obj in self.query.objs
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1359, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1310, in pre_save_val
return field.pre_save(obj, add=True)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\fields\__init__.py", line 822, in pre_save
return getattr(model_instance, self.attname)
Exception Type: AttributeError at /users/app_det/
Exception Value: 'Seekerskillset' object has no attribute 'skill_name'
The problem is caused by using Skillset to bulk create Seekerskillset objects.
So change:
seeker_skll = Skillset.objects.bulk_create(seeker_skll)
to:
seeker_skll = Seekerskillset.objects.bulk_create(seeker_skll)
I'm using Django 3 and Python 3.8 along with the Django rest framework. I have the following model. Notice the many-to-many relationship with addresses ...
class Coop(models.Model):
objects = CoopManager()
name = models.CharField(max_length=250, null=False)
types = models.ManyToManyField(CoopType, blank=False)
addresses = models.ManyToManyField(Address)
enabled = models.BooleanField(default=True, null=False)
phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone')
email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email')
web_site = models.TextField()
I have created the following serializers. I'm having trouble with updating the model so I exluded the create methods for simplicity ...
class AddressTypeField(serializers.PrimaryKeyRelatedField):
queryset = Address.objects
def to_internal_value(self, data):
if type(data) == dict:
locality = data['locality']
state = None if not re.match(r"[0-9]+", str(locality['state'])) else State.objects.get(pk=locality['state'])
locality['state'] = state
locality, created = Locality.objects.get_or_create(**locality)
data['locality'] = locality
address = Address.objects.create(**data)
# Replace the dict with the ID of the newly obtained object
data = address.pk
return super().to_internal_value(data)
...
class CoopSerializer(serializers.ModelSerializer):
types = CoopTypeSerializer(many=True, allow_empty=False)
addresses = AddressTypeField(many=True)
phone = ContactMethodPhoneSerializer()
email = ContactMethodEmailSerializer()
class Meta:
model = Coop
fields = '__all__'
...
def update(self, instance, validated_data):
"""
Update and return an existing `Coop` instance, given the validated data.
"""
instance.name = validated_data.get('name', instance.name)
try:
coop_types = validated_data['types']
instance.types.clear() # Disassociates all CoopTypes from instance.
for item in coop_types:
coop_type, _ = CoopType.objects.get_or_create(**item)
instance.types.add(coop_type)
except KeyError:
pass
instance.addresses = validated_data.get('addresses', instance.addresses)
instance.enabled = validated_data.get('enabled', instance.enabled)
phone = validated_data.pop('phone', {})
email = validated_data.pop('email', {})
instance.phone = ContactMethod.objects.create(type=ContactMethod.ContactTypes.PHONE, **phone)
instance.email = ContactMethod.objects.create(type=ContactMethod.ContactTypes.EMAIL, **email)
instance.web_site = validated_data.get('web_site', instance.web_site)
instance.web_site = validated_data.get('web_site', instance.web_site)
instance.save()
return instance
What's the right way to handle updating the address fields of my main Coop model? When I submit a payload like below (I have IDs included with my address member field objects) ...
{"id":927,"types":[{"id":76,"name":"ct"}],"addresses":[{"id":824,"street_number":"","route":"","raw":"","formatted":"4750 N Woodlawn Rd","latitude":null,"longitude":null,"locality":{"id":54,"name":"Chicago","postal_code":"60640","state":19313}}],"phone":{"phone":"3039468888"},"email":{"email":"dave#hello.com"},"name":"Dave Coop","enabled":true,"web_site":"http://www.example.org"}
And submit it via PATCH, I get the error below. Is there some way to tell my serializer to only update the member field if an ID is created instead of trying to create it from scratch each time?
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
raise exc
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/davea/Documents/workspace/chicommons/maps/web/directory/views.py", line 78, in put
if serializer.is_valid():
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 234, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 433, in run_validation
value = self.to_internal_value(data)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 490, in to_internal_value
validated_value = field.run_validation(primitive_value)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/fields.py", line 565, in run_validation
value = self.to_internal_value(data)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/relations.py", line 519, in to_internal_value
return [
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/relations.py", line 520, in <listcomp>
self.child_relation.to_internal_value(item)
File "/Users/davea/Documents/workspace/chicommons/maps/web/directory/serializers.py", line 35, in to_internal_value
address = Address.objects.create(**data)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 433, in create
obj.save(force_insert=True, using=self.db)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/base.py", line 745, in save
self.save_base(using=using, force_insert=force_insert,
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/base.py", line 782, in save_base
updated = self._save_table(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/base.py", line 886, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/base.py", line 923, in _do_insert
return manager._insert(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 1204, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1377, in execute_sql
cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 74, in execute
return self.cursor.execute(query, args)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymysql/cursors.py", line 170, in execute
result = self._query(query)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymysql/cursors.py", line 328, in _query
conn.query(q)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymysql/connections.py", line 517, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymysql/connections.py", line 732, in _read_query_result
result.read()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymysql/connections.py", line 1075, in read
first_packet = self.connection._read_packet()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymysql/connections.py", line 684, in _read_packet
packet.check_error()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymysql/protocol.py", line 220, in check_error
err.raise_mysql_exception(self._data)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pymysql/err.py", line 109, in raise_mysql_exception
raise errorclass(errno, errval)
django.db.utils.IntegrityError: (1062, "Duplicate entry '824' for key 'address_address.PRIMARY'")
try using partial=True in serializer
I have few django models:
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
phone = models.CharField(
_('phone number'), max_length=16,
unique=True, blank=True, null=True,
default=None, validators=[phone_validator]
)
...
class UserExtension(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
class Meta:
abstract = True
class Worker(UserExtension):
# some fields
class Administrator(UserExtension):
# some fields
View:
class AdministratorListView(ListAPIView):
permission_classes = (AllowAny,)
queryset = Administrator.objects.all()
serializer_class = serializers.AdministratorSerializer
And serializer:
class AdministratorSerializer(serializers.ModelSerializer):
class Meta:
model = Administrator
fields = ('network', 'email')
extra_kwargs = {'email': {'source': 'user.email'}}
But this is not working. Following traceback tell about field does not exist for my model:
Traceback (most recent call last):
File "/home/vagrant/v_env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/vagrant/v_env/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/vagrant/v_env/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/vagrant/v_env/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/vagrant/v_env/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/vagrant/v_env/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "/home/vagrant/v_env/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/vagrant/v_env/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "/home/vagrant/v_env/lib/python3.6/site-packages/rest_framework/generics.py", line 201, in get
return self.list(request, *args, **kwargs)
File "/home/vagrant/v_env/lib/python3.6/site-packages/rest_framework/mixins.py", line 48, in list
return Response(serializer.data)
File "/home/vagrant/v_env/lib/python3.6/site-packages/rest_framework/serializers.py", line 765, in data
ret = super(ListSerializer, self).data
File "/home/vagrant/v_env/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/home/vagrant/v_env/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in to_representation
self.child.to_representation(item) for item in iterable
File "/home/vagrant/v_env/lib/python3.6/site-packages/rest_framework/serializers.py", line 683, in <listcomp>
self.child.to_representation(item) for item in iterable
File "/home/vagrant/v_env/lib/python3.6/site-packages/rest_framework/serializers.py", line 510, in to_representation
fields = self._readable_fields
File "/home/vagrant/v_env/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/vagrant/v_env/lib/python3.6/site-packages/rest_framework/serializers.py", line 376, in _readable_fields
field for field in self.fields.values()
File "/home/vagrant/v_env/lib/python3.6/site-packages/rest_framework/serializers.py", line 363, in fields
for key, value in self.get_fields().items():
File "/home/vagrant/v_env/lib/python3.6/site-packages/rest_framework/serializers.py", line 1047, in get_fields
source, info, model, depth
File "/home/vagrant/v_env/lib/python3.6/site-packages/rest_framework/serializers.py", line 1192, in build_field
return self.build_unknown_field(field_name, model_class)
File "/home/vagrant/v_env/lib/python3.6/site-packages/rest_framework/serializers.py", line 1304, in build_unknown_field
(field_name, model_class.__name__)
django.core.exceptions.ImproperlyConfigured: Field name `user.email` is not valid for model `Administrator`.
I looked at the source code and realized that the value from 'source' is passed to build_field as field_name argument and rest-framework simply cannot find this field ('user.email') in my model (Administrator)
part of get_fields method
build_field method
I have this Serializer:
class LikeSerializer(serializers.ModelSerializer):
user = serializers.PrimaryKeyRelatedField(queryset=ExtUser.objects.all(), required=False, allow_null=True, default=None)
class Meta:
model = Like
field = ('user', 'post')
def create(self, validated_data):
post = Post(id=validated_data['post'], author=validated_data['user'])
#post=Post.objects.get(pk=validated_data['post'])
post.rating += 1
print(post)
post.save()
return Like.objects.create(**validated_data)
And I get error, when i trying to save Like object TypeError: int() argument must be a string or a number, not 'Post'
Trying to add int(), but it not helps, I think I not correct update Post object
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 466, in dispatch
response = self.handle_exception(exc)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 463, in dispatch
response = handler(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/decorators.py", line 53, in handler
return func(*args, **kwargs)
File "/Users/olegklimakov/Documents/6rp/likes/views.py", line 19, in send_like
serializer.save(user=request.user, isLiked=True)
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 191, in save
self.instance = self.create(validated_data)
File "/Users/olegklimakov/Documents/6rp/likes/serializers.py", line 39, in create
post.save()
File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 700, in save
force_update=force_update, update_fields=update_fields)
File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 728, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 793, in _save_table
forced_update)
File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 823, in _do_update
filtered = base_qs.filter(pk=pk_val)
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 790, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 808, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 1243, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 1269, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 1203, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 1099, in build_lookup
return final_lookup(lhs, rhs)
File "/Library/Python/2.7/site-packages/django/db/models/lookups.py", line 19, in __init__
self.rhs = self.get_prep_lookup()
File "/Library/Python/2.7/site-packages/django/db/models/lookups.py", line 57, in get_prep_lookup
return self.lhs.output_field.get_prep_lookup(self.lookup_name, self.rhs)
File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 744, in get_prep_lookup
return self.get_prep_value(value)
File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 976, in get_prep_value
return int(value)
TypeError: int() argument must be a string or a number, not 'Post'
Post model:
class Post(models.Model):
id = models.AutoField(primary_key=True)
date_create = models.DateField(auto_now_add=True)
date_change = models.DateField(auto_now=True)
title = models.CharField(max_length=250) # Max Length of title = 250
description = models.CharField(max_length=1000) # Max Length = 1000 chars
rating = models.IntegerField(default=1)
author = models.ForeignKey('extuser.ExtUser', blank=True, null=True)
def __unicode__(self):
return u"%s" % self.id
It seems like inside the statement
"Post(id=validated_data['post'], author=validated_data['user'])",
validated_data['post'] gives you a Post object, not a int object,
but the 'id' inside the Post model expect a int object.
That probably is the reason you get the error.
#transactional
def create(self, validated_data):
post = Post(id=validated_data['post'], author=validated_data['user'])
post.rating += 1
post.save()
return super(self, LikeSerializer).create(validated_data)
Its good to let ModelSerializer create do its job, also note you definitely want to use transaction to keep data consistent
Also, code below creates new Post entity:
post = Post(...)
post.save()
You definitely need to get existent Post entity instead
Post.objects.filter(...).first()