mirror of
https://github.com/netbox-community/netbox.git
synced 2024-05-10 07:54:54 +00:00
Fixes #1421: Improved model validation logic for API serializers
This commit is contained in:
@ -8,7 +8,7 @@ from rest_framework.compat import is_authenticated
|
||||
from rest_framework.exceptions import APIException
|
||||
from rest_framework.pagination import LimitOffsetPagination
|
||||
from rest_framework.permissions import BasePermission, DjangoModelPermissions, SAFE_METHODS
|
||||
from rest_framework.serializers import Field, ValidationError
|
||||
from rest_framework.serializers import Field, ModelSerializer, ValidationError
|
||||
|
||||
from users.models import Token
|
||||
|
||||
@ -80,6 +80,21 @@ class IsAuthenticatedOrLoginNotRequired(BasePermission):
|
||||
# Serializers
|
||||
#
|
||||
|
||||
class ValidatedModelSerializer(ModelSerializer):
|
||||
"""
|
||||
Extends the built-in ModelSerializer to enforce calling clean() on the associated model during validation.
|
||||
"""
|
||||
def validate(self, attrs):
|
||||
if self.instance is None:
|
||||
instance = self.Meta.model(**attrs)
|
||||
else:
|
||||
instance = self.instance
|
||||
for k, v in attrs.items():
|
||||
setattr(instance, k, v)
|
||||
instance.clean()
|
||||
return attrs
|
||||
|
||||
|
||||
class ChoiceFieldSerializer(Field):
|
||||
"""
|
||||
Represent a ChoiceField as {'value': <DB value>, 'label': <string>}.
|
||||
@ -121,17 +136,6 @@ class ContentTypeFieldSerializer(Field):
|
||||
# Mixins
|
||||
#
|
||||
|
||||
class ModelValidationMixin(object):
|
||||
"""
|
||||
Enforce a model's validation through clean() when validating serializer data. This is necessary to ensure we're
|
||||
employing the same validation logic via both forms and the API.
|
||||
"""
|
||||
def validate(self, attrs):
|
||||
instance = self.Meta.model(**attrs)
|
||||
instance.clean()
|
||||
return attrs
|
||||
|
||||
|
||||
class WritableSerializerMixin(object):
|
||||
"""
|
||||
Allow for the use of an alternate, writable serializer class for write operations (e.g. POST, PUT).
|
||||
|
Reference in New Issue
Block a user