add support for svg images in library
This commit is contained in:
parent
2c217939b0
commit
ff3a09d30c
7 changed files with 257 additions and 30 deletions
|
@ -2,6 +2,8 @@ from django.db import models
|
|||
from django.core.exceptions import ValidationError
|
||||
from django.utils.text import slugify
|
||||
from django_prose_editor.fields import ProseEditorField
|
||||
import mimetypes
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
|
||||
def validate_image_size(value, mb=1):
|
||||
|
@ -10,6 +12,49 @@ def validate_image_size(value, mb=1):
|
|||
raise ValidationError(f"Maximum file size is {mb} MB")
|
||||
|
||||
|
||||
def validate_image_or_svg(value):
|
||||
"""
|
||||
Validate that the uploaded file is either a valid image or SVG file.
|
||||
"""
|
||||
# Check file size first
|
||||
validate_image_size(value)
|
||||
|
||||
# Get the file extension and MIME type
|
||||
filename = value.name.lower()
|
||||
mime_type, _ = mimetypes.guess_type(filename)
|
||||
|
||||
# List of allowed image formats
|
||||
allowed_image_types = [
|
||||
"image/jpeg",
|
||||
"image/png",
|
||||
"image/gif",
|
||||
"image/webp",
|
||||
"image/bmp",
|
||||
"image/tiff",
|
||||
"image/svg+xml",
|
||||
]
|
||||
|
||||
# Check if it's an SVG file
|
||||
if filename.endswith(".svg") or mime_type == "image/svg+xml":
|
||||
try:
|
||||
# Reset file pointer and read content
|
||||
value.seek(0)
|
||||
content = value.read()
|
||||
value.seek(0) # Reset for later use
|
||||
|
||||
# Try to parse as XML to ensure it's valid SVG
|
||||
ET.fromstring(content)
|
||||
return # Valid SVG
|
||||
except ET.ParseError:
|
||||
raise ValidationError("Invalid SVG file format")
|
||||
|
||||
# For non-SVG files, check MIME type
|
||||
if mime_type not in allowed_image_types:
|
||||
raise ValidationError(
|
||||
f"Unsupported file type. Allowed types: JPEG, PNG, GIF, WebP, BMP, TIFF, SVG"
|
||||
)
|
||||
|
||||
|
||||
class Currency(models.TextChoices):
|
||||
CHF = "CHF", "Swiss Franc"
|
||||
EUR = "EUR", "Euro"
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue