Skip to content

Commit d12439f

Browse files
Modified the thumbnail field and fixed the duplication of the name category integrity error!
1 parent f714a20 commit d12439f

File tree

2 files changed

+21
-9
lines changed

2 files changed

+21
-9
lines changed

shop/serializers.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,13 @@ class ProductSerializer(serializers.ModelSerializer):
3232
rating = serializers.SerializerMethodField()
3333

3434
slug = serializers.ReadOnlyField()
35-
thumbnail_url = serializers.SerializerMethodField(read_only=True)
35+
thumbnail = serializers.ImageField(
36+
allow_null=True,
37+
required=False,
38+
use_url=True,
39+
max_length=255,
40+
help_text="URL of the product thumbnail image."
41+
)
3642
detail_url = serializers.URLField(source='get_absolute_url', read_only=True)
3743

3844
@extend_schema_field(serializers.DictField(child=serializers.FloatField()))
@@ -88,12 +94,6 @@ def update(self, instance, validated_data):
8894
instance.tags.clear()
8995
return super().update(instance, validated_data)
9096

91-
@extend_schema_field(serializers.CharField(allow_null=True))
92-
def get_thumbnail_url(self, obj):
93-
if obj.thumbnail and hasattr(obj.thumbnail, 'url'):
94-
return obj.thumbnail.url
95-
return None
96-
9797
class Meta:
9898
model = Product
9999
fields = [
@@ -103,7 +103,7 @@ class Meta:
103103
'description',
104104
'price',
105105
'stock',
106-
'thumbnail_url',
106+
'thumbnail',
107107
'detail_url',
108108
'category',
109109
'category_detail',
@@ -147,4 +147,4 @@ def get_recommended_products(self, obj):
147147
return ProductSerializer(suggested_products, many=True, context=self.context).data
148148

149149
class Meta(ProductSerializer.Meta):
150-
fields = ProductSerializer.Meta.fields + ['recommended_products']
150+
fields = ProductSerializer.Meta.fields + ['recommended_products', 'reviews']

shop/views.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,3 +435,15 @@ def list(self, request, *args, **kwargs):
435435
except Exception as e:
436436
logger.error("Error listing categories: %s", e, exc_info=True)
437437
raise
438+
439+
def perform_create(self, serializer):
440+
from django.db import IntegrityError
441+
from rest_framework.exceptions import ValidationError
442+
try:
443+
serializer.save()
444+
except IntegrityError as e:
445+
logger.error("Integrity error creating category: %s", e, exc_info=True)
446+
raise ValidationError({"name": "A category with this name or slug already exists."})
447+
except Exception as e:
448+
logger.error("Error creating category: %s", e, exc_info=True)
449+
raise

0 commit comments

Comments
 (0)