Move validation to the model class

This commit is contained in:
Oliver 2021-11-28 22:29:01 +11:00
parent 4ee55847f1
commit 78309c1915
3 changed files with 17 additions and 18 deletions

View File

@ -98,6 +98,7 @@ class InvenTreeAttachment(models.Model):
user: User associated with file upload
upload_date: Date the file was uploaded
"""
def getSubdir(self):
"""
Return the subdirectory under which attachments should be stored.
@ -106,6 +107,16 @@ class InvenTreeAttachment(models.Model):
return "attachments"
def save(self, *args, **kwargs):
# Either 'attachment' or 'link' must be specified!
if not self.attachment and not self.link:
raise ValidationError({
'attachment': _('Missing file'),
'link': _('Missing external link'),
})
super().save(*args, **kwargs)
def __str__(self):
if self.attachment is not None:
return os.path.basename(self.attachment.name)

View File

@ -275,24 +275,6 @@ class InvenTreeAttachmentSerializer(InvenTreeModelSerializer):
The only real addition here is that we support "renaming" of the attachment file.
"""
def validate(self, data):
"""
Validation for an attachment. Either a file or external link must be provided
"""
data = super().validate(data)
attachment = data.get('attachment', None)
link = data.get('link', None)
if not attachment and not link:
raise ValidationError({
'attachment': _('Missing file'),
'link': _('Missing external link'),
})
return data
attachment = InvenTreeAttachmentSerializerField(
required=False,
allow_null=False,

View File

@ -88,6 +88,12 @@ function loadAttachmentTable(url, options) {
link: {},
comment: {},
},
processResults: function(data, fields, opts) {
// Remove the "link" field if the attachment is a file!
if (data.attachment) {
delete opts.fields.link;
}
},
onSuccess: reloadAttachmentTable,
title: '{% trans "Edit Attachment" %}',
});