在Modelviewset中进行验证

时间:2019-10-01 09:41:53

标签: python django django-rest-framework

我必须验证图像。我尝试将验证器添加到models.py的字段中,但是python无法migrate验证器,具体取决于类。在这种情况下,如何在views.py

中添加验证

validators.py

class ValidateImageSize:
    MEASURE_UNIT_BYTE_MAP = {
        'kb': 1024,
        'mb': 1024 * 1024,
    }
    MEASURE_UNIT_NAME_MAP = {
        'kb': 'kilobyte',
        'mb': 'megabyte',
    }

    def __init__(self, max_size):
        max_size, measure_unit = max_size.split(' ')
        self.max_size = int(max_size)
        self.measure_unit = measure_unit

    def __call__(self, value):
        if value.size > self.max_size * self.MEASURE_UNIT_BYTE_MAP[self.measure_unit]:
            raise ValidationError(f'Size maximum is {self.max_size} {self.measure_unit}')

views.py

class EpisodeView(viewsets.ModelViewSet):
    def create(self, request, story_id=None, *args, **kwargs):
        try:
            story = Story.objects.get(pk=story_id)
        except Story.DoesNotExist:
            raise NotFound

        kwargs = {
            'story': story,
            'title': request.data.get('title'),
            'cover': request.data.get('cover'),
        }

        episode = Episode.objects.create(**kwargs)

        for image in dict(request.data.lists())['images']:
            EpisodeImage.objects.create(episode=episode, image=image)

        return Response({'episode_id': episode.id}, status=201)

1 个答案:

答案 0 :(得分:1)

首先,我们将验证所有图像的大小/格式是否正确,如果没有错误,则进行创建操作。

from .validators import  ValidateImageSize

class EpisodeView(viewsets.ModelViewSet):
    def create(self, request, story_id=None, *args, **kwargs):
        try:
            story = Story.objects.get(pk=story_id)
        except Story.DoesNotExist:
            raise NotFound
        # now we will run image validation 
        custom_image_validator = ValidateImageSize() # with your desize size
        for image in dict(request.data.lists())['images']:
            custom_image_validator(image) # this will raise validation error if any validation error occur 

        # After that will do our regular work

        kwargs = {
            'story': story,
            'title': request.data.get('title'),
            'cover': request.data.get('cover'),
        }

        episode = Episode.objects.create(**kwargs)

        for image in dict(request.data.lists())['images']:
            EpisodeImage.objects.create(episode=episode, image=image)

        return Response({'episode_id': episode.id}, status=201)