class ImageGallerySerializer(DispatchModelSerializer): """Serializes the ImageGallery model without including full Image instance.""" images = ImageAttachmentSerializer(read_only=True, many=True) attachment_json = JSONField(required=False, write_only=True, validators=[ImageGalleryValidator]) class Meta: model = ImageGallery fields = ('id', 'title', 'images', 'attachment_json') def create(self, validated_data): # Create new ImageGallery instance instance = ImageGallery() # Then save as usual return self.update(instance, validated_data) def update(self, instance, validated_data): # Update all the basic fields instance.title = validated_data.get('title', instance.title) # Save instance before processing/saving content in order to # save associations to correct ID instance.save() attachment_json = validated_data.get('attachment_json', False) if isinstance(attachment_json, list): instance.save_attachments(attachment_json) return instance
class PollSerializer(DispatchModelSerializer): """Serializes the Poll model.""" answers = serializers.SerializerMethodField() answers_json = JSONField(required=False, write_only=True) total_votes = serializers.SerializerMethodField() question = serializers.CharField(required=True) name = serializers.CharField(required=True) class Meta: model = Poll fields = ('id', 'is_open', 'show_results', 'name', 'question', 'answers', 'answers_json', 'total_votes') def get_total_votes(self, obj): total_votes = 0 if self.is_authenticated() or obj.show_results: total_votes = obj.get_total_votes() return total_votes def get_answers(self, obj): answers = PollAnswer.objects.filter(poll_id=obj.id) serializer = PollAnswerSerializer(answers, many=True, context=self.context) return serializer.data def create(self, validated_data): # Create new ImageGallery instance instance = Poll() # Then save as usual return self.update(instance, validated_data, True) def update(self, instance, validated_data, is_new=False): # Update all the basic fields instance.question = validated_data.get('question', instance.question) instance.name = validated_data.get('name', instance.name) instance.is_open = validated_data.get('is_open', instance.is_open) instance.show_results = validated_data.get('show_results', instance.show_results) # Save instance before processing/saving content in order to # save associations to correct ID instance.save() answers = validated_data.get('answers_json') if isinstance(answers, list): instance.save_answers(answers, is_new) return instance
class IntegrationSerializer(serializers.Serializer): id = serializers.CharField(source='ID', read_only=True) settings = JSONField(source='get_settings') def save(self): settings = self.validated_data.get('get_settings') if settings: self.instance.save(settings) return self.instance
class ZoneSerializer(serializers.Serializer): id = serializers.SlugField(read_only=True) name = serializers.CharField(read_only=True) widget = PrimaryKeyField( allow_null=True, serializer=WidgetSerializer(allow_null=True)) data = JSONField(required=False) def validate(self, data): """Perform validation of the widget data""" from dispatch.theme import ThemeManager errors = {} if data.get('widget') is not None: try: widget = ThemeManager.Widgets.get(data['widget']) except WidgetNotFound as e: errors['widget'] = str(e) else: for field in widget.fields: field_data = data['data'].get(field.name) if field_data is not None: try: field.validate(field_data) except InvalidField as e: errors[field.name] = str(e) elif field.required: errors[field.name] = '%s is required' % field.label if errors: raise ValidationError(errors) return data def update(self, instance, validated_data): widget = validated_data.get('widget') if not widget: instance.delete() else: instance.save(validated_data) return instance
class PageSerializer(DispatchModelSerializer, DispatchPublishableSerializer): """Serializes the Page model.""" id = serializers.ReadOnlyField(source='parent_id') slug = serializers.SlugField(validators=[SlugValidator()]) is_published = NullBooleanField(read_only=True) featured_image = ImageAttachmentSerializer(required=False, allow_null=True) featured_video = VideoAttachmentSerializer(required=False, allow_null=True) content = ContentSerializer() url = serializers.CharField(source='get_absolute_url', read_only=True) current_version = serializers.IntegerField(read_only=True, source='revision_id') template = TemplateSerializer(required=False, source='get_template') template_id = serializers.CharField(required=False, write_only=True) template_data = JSONField(required=False) updated_at = serializers.DateTimeField(read_only=True) class Meta: model = Page fields = ('id', 'slug', 'url', 'title', 'featured_image', 'featured_video', 'snippet', 'content', 'published_at', 'updated_at', 'is_published', 'published_version', 'current_version', 'latest_version', 'preview_id', 'template', 'template_id', 'template_data', 'seo_keyword', 'seo_description') authenticated_fields = ('template', 'preview_id') def create(self, validated_data): instance = Page() return self.update(instance, validated_data) def update(self, instance, validated_data): # Update all the basic fields instance.title = validated_data.get('title', instance.title) instance.slug = validated_data.get('slug', instance.slug) instance.snippet = validated_data.get('snippet', instance.snippet) instance.seo_keyword = validated_data.get('seo_keyword', instance.seo_keyword) instance.seo_description = validated_data.get('seo_description', instance.seo_description) instance.template = validated_data.get('template_id', instance.template) instance.template_data = validated_data.get('template_data', instance.template_data) # Save instance before processing/saving content in order to save associations to correct ID instance.save() instance.content = validated_data.get('content', instance.content) featured_image = validated_data.get('featured_image', False) if featured_image != False: instance.save_featured_image(featured_image) featured_video = validated_data.get('featured_video', False) if featured_video != False: instance.save_featured_video(featured_video) # Perform a final save (without revision), update content and featured image instance.save( update_fields=['content', 'featured_image', 'featured_video'], revision=False) return instance
class ArticleSerializer(DispatchModelSerializer, DispatchPublishableSerializer): """Serializes the Article model.""" id = serializers.ReadOnlyField(source='parent_id') slug = serializers.SlugField(validators=[SlugValidator()]) is_published = NullBooleanField(read_only=True) section = SectionSerializer(read_only=True) section_id = serializers.IntegerField(write_only=True) subsection = SubsectionSerializer(source='get_subsection', read_only=True) subsection_id = serializers.IntegerField(write_only=True, required=False, allow_null=True) featured_image = ImageAttachmentSerializer(required=False, allow_null=True) featured_video = VideoAttachmentSerializer(required=False, allow_null=True) content = ContentSerializer() authors = AuthorSerializer(many=True, read_only=True) author_ids = serializers.ListField(write_only=True, child=serializers.JSONField(), validators=[AuthorValidator]) authors_string = serializers.CharField(source='get_author_string', read_only=True) tags = TagSerializer(many=True, read_only=True) tag_ids = serializers.ListField(write_only=True, required=False, child=serializers.IntegerField()) topic = TopicSerializer(read_only=True) topic_id = serializers.IntegerField(write_only=True, allow_null=True, required=False) url = serializers.CharField(source='get_absolute_url', read_only=True) current_version = serializers.IntegerField(read_only=True, source='revision_id') template = TemplateSerializer(required=False, source='get_template') template_id = serializers.CharField(required=False, write_only=True) template_data = JSONField(required=False) integrations = JSONField(required=False) currently_breaking = serializers.BooleanField( source='is_currently_breaking', read_only=True) class Meta: model = Article fields = ('id', 'slug', 'url', 'headline', 'featured_image', 'featured_video', 'snippet', 'content', 'authors', 'author_ids', 'tags', 'tag_ids', 'topic', 'topic_id', 'authors_string', 'section', 'section_id', 'subsection', 'subsection_id', 'published_at', 'is_published', 'is_breaking', 'breaking_timeout', 'currently_breaking', 'published_version', 'current_version', 'latest_version', 'preview_id', 'importance', 'reading_time', 'template', 'template_id', 'template_data', 'seo_keyword', 'seo_description', 'integrations') authenticated_fields = ('template', 'integrations', 'preview_id') def create(self, validated_data): instance = Article() return self.update(instance, validated_data) def update(self, instance, validated_data): template = validated_data.get('template_id', instance.template) template_data = validated_data.get('template_data', instance.template_data) tag_ids = validated_data.get('tag_ids', False) tags = [] if tag_ids != False: for tag_id in tag_ids: try: tags.append(Tag.objects.get(id=int(tag_id))) except Tag.DoesNotExist: pass subsection_id = validated_data.get('subsection_id', None) TemplateValidator(template, template_data, tags, subsection_id) section_id = validated_data.get('section_id', instance.section_id) SectionValidator(section_id, subsection_id, template, tags) # Update basic fields instance.headline = validated_data.get('headline', instance.headline) instance.section_id = section_id instance.slug = validated_data.get('slug', instance.slug) instance.snippet = validated_data.get('snippet', instance.snippet) instance.reading_time = validated_data.get('reading_time', instance.reading_time) instance.importance = validated_data.get('importance', instance.importance) instance.is_breaking = validated_data.get('is_breaking', instance.is_breaking) instance.breaking_timeout = validated_data.get( 'breaking_timeout', instance.breaking_timeout) instance.seo_keyword = validated_data.get('seo_keyword', instance.seo_keyword) instance.seo_description = validated_data.get('seo_description', instance.seo_description) instance.integrations = validated_data.get('integrations', instance.integrations) instance.template = template instance.template_data = template_data instance.save() instance.content = validated_data.get('content', instance.content) featured_image = validated_data.get('featured_image', False) if featured_image != False: instance.save_featured_image(featured_image) featured_video = validated_data.get('featured_video', False) if featured_video != False: instance.save_featured_video(featured_video) authors = validated_data.get('author_ids') if authors: instance.save_authors(authors, is_publishable=True) if tag_ids != False: instance.save_tags(tag_ids) topic_id = validated_data.get('topic_id', False) if topic_id != False: instance.save_topic(topic_id) subsection_id = validated_data.get('subsection_id', None) instance.save_subsection(subsection_id) # Perform a final save (without revision), update content and featured image instance.save(update_fields=[ 'content', 'featured_image', 'featured_video', 'topic' ], revision=False) return instance