diff --git a/InvenTree/InvenTree/fields.py b/InvenTree/InvenTree/fields.py index 6c62aacb9d..35f9fb5eb4 100644 --- a/InvenTree/InvenTree/fields.py +++ b/InvenTree/InvenTree/fields.py @@ -12,12 +12,21 @@ from django.utils.translation import gettext_lazy as _ from djmoney.forms.fields import MoneyField from djmoney.models.fields import MoneyField as ModelMoneyField from djmoney.models.validators import MinMoneyValidator +from rest_framework.fields import URLField as RestURLField import InvenTree.helpers from .validators import allowable_url_schemes +class InvenTreeRestURLField(RestURLField): + """Custom field for DRF with custom scheme vaildators.""" + def __init__(self, **kwargs): + """Update schemes.""" + super().__init__(**kwargs) + self.validators[-1].schemes = allowable_url_schemes() + + class InvenTreeURLFormField(FormURLField): """Custom URL form field with custom scheme validators.""" @@ -27,7 +36,7 @@ class InvenTreeURLFormField(FormURLField): class InvenTreeURLField(models.URLField): """Custom URL field which has custom scheme validators.""" - default_validators = [validators.URLValidator(schemes=allowable_url_schemes())] + validators = [validators.URLValidator(schemes=allowable_url_schemes())] def formfield(self, **kwargs): """Return a Field instance for this field.""" diff --git a/InvenTree/InvenTree/serializers.py b/InvenTree/InvenTree/serializers.py index d890f9f478..385d2f4837 100644 --- a/InvenTree/InvenTree/serializers.py +++ b/InvenTree/InvenTree/serializers.py @@ -7,6 +7,7 @@ from decimal import Decimal from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import ValidationError as DjangoValidationError +from django.db import models from django.utils.translation import gettext_lazy as _ import tablib @@ -20,6 +21,7 @@ from rest_framework.serializers import DecimalField from rest_framework.utils import model_meta from common.models import InvenTreeSetting +from InvenTree.fields import InvenTreeRestURLField from InvenTree.helpers import download_image_from_url @@ -64,6 +66,12 @@ class InvenTreeMoneySerializer(MoneyField): class InvenTreeModelSerializer(serializers.ModelSerializer): """Inherits the standard Django ModelSerializer class, but also ensures that the underlying model class data are checked on validation.""" + # Switch out URLField mapping + serializer_field_mapping = { + **serializers.ModelSerializer.serializer_field_mapping, + models.URLField: InvenTreeRestURLField, + } + def __init__(self, instance=None, data=empty, **kwargs): """Custom __init__ routine to ensure that *default* values (as specified in the ORM) are used by the DRF serializers, *if* the values are not provided by the user.""" # If instance is None, we are creating a new instance