【问题标题】:Django Admin and ImageField dimension restrictionsDjango Admin 和 ImageField 维度限制
【发布时间】:2016-09-24 14:18:51
【问题描述】:

我正在使用 Django 1.10.1。

我有一个带有 ImageField 的模型,当有人尝试在 Django 管理站点中上传大于 900x900px 的文件时,我想触发一个错误。

最简单的方法是什么?我更愿意在 Model 类中执行此操作,因为它永远不应该被允许保存更大的图像,但我在某处读到它是不可能的,因为只要数据没有保存,你就无法访问图像数据。

【问题讨论】:

    标签: python django django-admin


    【解决方案1】:

    对于 Django 2 及更高版本,可以使用一种更简单的方法来解决此问题。 只要记住 2 Scoops of Django 的 FAT 模型哲学。使用 models.py 并为 ImageField 包含一个自定义验证,然后可以将它用于您创建的其他模型的任何相关 ImageField。因此,表单和管理员自然会运行此验证并输出错误

    示例代码

    将其插入到在您的应用下创建的名为 validators.py 的新文件中

    from django.core.exceptions import ValidationError
    from django.core.files.images import get_image_dimensions
    
    def image_restriction(image):
        image_width, image_height = get_image_dimensions(image)
        if image_width >= ??? or image_height >= ???:
            raise ValidationError('Image width needs to be less than 128px')
    

    然后在您的模型中简单地导入并包含

    from apps.assessment.validators import image_restriction
    
    image = models.ImageField(
        validators=[image_restriction],
        upload_to='assessment_images'
    )
    

    【讨论】:

      【解决方案2】:

      您可以覆盖 ModelAdmin 类的表单并验证您的图像尺寸。

      from django.contrib import admin
      from django import forms
      from django.core.files.images import get_image_dimensions
      
      from .models import ModelWithImageField
      
      
      class ModelWithImageFieldForm(forms.ModelForm):
          class Meta: 
              model = ModelWithImageField
              fields = '__all__'
      
          def clean_photo(self):
              photo = self.cleaned_data["photo"] 
              width, height = get_image_dimensions(photo.file)
              if width < 900 or height < 900:
                  raise form.ValidationError("Improper size.")
              return photo
      
      
      @admin.register(models.ModelWithImageField)
      class ModelWithImageFieldAdmin(admin.ModelAdmin):
          form = ModelWithImageFieldForm
      

      【讨论】:

        猜你喜欢
        • 2019-03-24
        • 1970-01-01
        • 2013-04-24
        • 2015-01-08
        • 1970-01-01
        • 2015-02-21
        • 1970-01-01
        • 2011-02-08
        相关资源
        最近更新 更多