freekake_api/freekake_api/content/serializers.py

30 lines
1.2 KiB
Python

from django.forms import ImageField
from rest_framework import serializers
from content import models
class ContentSerializer(serializers.ModelSerializer):
featured_image = ImageField(max_length=255, allow_empty_file=False)
class Meta:
model = models.Content
fields = ['id', 'title', 'slug', 'featured_image', 'theme', 'topic', 'format', 'description','content', 'point', 'coin', 'data', 'grades', 'color']
class ContentDetailSerializer(serializers.ModelSerializer):
featured_image = ImageField(max_length=255, allow_empty_file=False)
class Meta:
model = models.Content
fields = ['id', 'title', 'slug', 'featured_image', 'theme', 'topic', 'format', 'description','content', 'point', 'coin', 'data', 'grades', 'color']
def validate(self, data):
theme = data.get('theme')
topic = data.get('topic')
allowed_topics = dict(models.Content.CONTENT_TOPIC_CHOICES).get(theme, [])
valid_topic_keys = [key for key, _ in allowed_topics]
if topic not in valid_topic_keys:
raise serializers.ValidationError({'topic': f'Topic "{topic}" is not valid for theme "{theme}"'})
return data