mirror of
https://github.com/netbox-community/netbox.git
synced 2024-05-10 07:54:54 +00:00
Implemented API endpoints for ImageAttachments
This commit is contained in:
@@ -1,9 +1,14 @@
|
||||
from rest_framework import serializers
|
||||
|
||||
from dcim.api.serializers import NestedSiteSerializer
|
||||
from extras.models import ACTION_CHOICES, Graph, GRAPH_TYPE_CHOICES, ExportTemplate, TopologyMap, UserAction
|
||||
from django.core.exceptions import ObjectDoesNotExist
|
||||
|
||||
from dcim.api.serializers import NestedDeviceSerializer, NestedRackSerializer, NestedSiteSerializer
|
||||
from dcim.models import Device, Rack, Site
|
||||
from extras.models import (
|
||||
ACTION_CHOICES, ExportTemplate, Graph, GRAPH_TYPE_CHOICES, ImageAttachment, TopologyMap, UserAction,
|
||||
)
|
||||
from users.api.serializers import NestedUserSerializer
|
||||
from utilities.api import ChoiceFieldSerializer
|
||||
from utilities.api import ChoiceFieldSerializer, ContentTypeFieldSerializer
|
||||
|
||||
|
||||
#
|
||||
@@ -71,6 +76,52 @@ class WritableTopologyMapSerializer(serializers.ModelSerializer):
|
||||
fields = ['id', 'name', 'slug', 'site', 'device_patterns', 'description']
|
||||
|
||||
|
||||
#
|
||||
# Image attachments
|
||||
#
|
||||
|
||||
class ImageAttachmentSerializer(serializers.ModelSerializer):
|
||||
parent = serializers.SerializerMethodField()
|
||||
|
||||
class Meta:
|
||||
model = ImageAttachment
|
||||
fields = ['id', 'parent', 'name', 'image', 'image_height', 'image_width', 'created']
|
||||
|
||||
def get_parent(self, obj):
|
||||
|
||||
# Static mapping of models to their nested serializers
|
||||
if isinstance(obj.parent, Device):
|
||||
serializer = NestedDeviceSerializer
|
||||
elif isinstance(obj.parent, Rack):
|
||||
serializer = NestedRackSerializer
|
||||
elif isinstance(obj.parent, Site):
|
||||
serializer = NestedSiteSerializer
|
||||
else:
|
||||
raise Exception("Unexpected type of parent object for ImageAttachment")
|
||||
|
||||
return serializer(obj.parent, context={'request': self.context['request']}).data
|
||||
|
||||
|
||||
class WritableImageAttachmentSerializer(serializers.ModelSerializer):
|
||||
content_type = ContentTypeFieldSerializer()
|
||||
|
||||
class Meta:
|
||||
model = ImageAttachment
|
||||
fields = ['id', 'content_type', 'object_id', 'name', 'image']
|
||||
|
||||
def validate(self, data):
|
||||
|
||||
# Validate that the parent object exists
|
||||
try:
|
||||
data['content_type'].get_object_for_this_type(id=data['object_id'])
|
||||
except ObjectDoesNotExist:
|
||||
raise serializers.ValidationError(
|
||||
"Invalid parent object: {} ID {}".format(data['content_type'], data['object_id'])
|
||||
)
|
||||
|
||||
return data
|
||||
|
||||
|
||||
#
|
||||
# User actions
|
||||
#
|
||||
|
Reference in New Issue
Block a user