New custom serializer for handling attachments

This commit is contained in:
Oliver 2021-08-15 22:43:52 +10:00
parent 81a8aac623
commit ff8dcabb12
4 changed files with 46 additions and 1 deletions

View File

@ -55,6 +55,20 @@ class InvenTreeAttachment(models.Model):
return "attachments"
def get_filename(self):
return os.path.basename(self.attachment.name)
def rename(self, filename):
"""
Rename this attachment with the provided filename.
- Filename cannot be empty
- Filename must have an extension
- Filename will have random data appended if a file exists with the same name
"""
pass
def __str__(self):
return os.path.basename(self.attachment.name)

View File

@ -208,6 +208,32 @@ class InvenTreeModelSerializer(serializers.ModelSerializer):
return data
class InvenTreeAttachmentSerializer(InvenTreeModelSerializer):
"""
Special case of an InvenTreeModelSerializer, which handles an "attachment" model.
The only real addition here is that we support "renaming" of the attachment file.
"""
# The 'filename' field must be present in the serializer
filename = serializers.CharField(
label=_('Filename'),
required=False,
source='get_filename',
)
def update(self, instance, validated_data):
"""
Filename can only be edited on "update"
"""
instance = super().update(instance, validated_data)
print(validated_data)
return instance
class InvenTreeAttachmentSerializerField(serializers.FileField):
"""
Override the DRF native FileField serializer,

View File

@ -1,6 +1,7 @@
"""
JSON serializers for Part app
"""
import imghdr
from decimal import Decimal
@ -16,7 +17,9 @@ from djmoney.contrib.django_rest_framework import MoneyField
from InvenTree.serializers import (InvenTreeAttachmentSerializerField,
InvenTreeImageSerializerField,
InvenTreeModelSerializer,
InvenTreeAttachmentSerializer,
InvenTreeMoneySerializer)
from InvenTree.status_codes import BuildStatus, PurchaseOrderStatus
from stock.models import StockItem
@ -51,7 +54,7 @@ class CategorySerializer(InvenTreeModelSerializer):
]
class PartAttachmentSerializer(InvenTreeModelSerializer):
class PartAttachmentSerializer(InvenTreeAttachmentSerializer):
"""
Serializer for the PartAttachment class
"""
@ -65,6 +68,7 @@ class PartAttachmentSerializer(InvenTreeModelSerializer):
'pk',
'part',
'attachment',
'filename',
'comment',
'upload_date',
]

View File

@ -868,6 +868,7 @@
constructForm(url, {
fields: {
filename: {},
comment: {},
},
title: '{% trans "Edit Attachment" %}',