代码之家  ›  专栏  ›  技术社区  ›  Apreche

在django admin中验证图像大小

  •  20
  • Apreche  · 技术社区  · 16 年前

    我看到很多人使用Django应用程序上传图像后会自动调整图像大小。这在某些情况下是好的,但我不想这样做。相反,我只是想强迫用户上传一个已经大小合适的文件。

    我希望有一个ImageField,在这里我强制用户上传100x200的图像。如果他们上传的图像大小不完全相同,我希望管理员表单返回为无效。我也希望能够为纵横比做同样的事情。我想强制用户上传16:9的图像,并拒绝任何不符合要求的上传。

    3 回复  |  直到 16 年前
        1
  •  56
  •   Flimm D. Ben Knoble    9 年前

    执行此操作的正确位置是在表单验证期间。
    一个快速示例(稍后将编辑/集成更多信息):

    from django.core.files.images import get_image_dimensions
    from django.contrib import admin
    from django import forms
    
    class myForm(forms.ModelForm):
       class Meta:
           model = myModel
       def clean_picture(self):
           picture = self.cleaned_data.get("picture")
           if not picture:
               raise forms.ValidationError("No image!")
           else:
               w, h = get_image_dimensions(picture)
               if w != 100:
                   raise forms.ValidationError("The image is %i pixel wide. It's supposed to be 100px" % w)
               if h != 200:
                   raise forms.ValidationError("The image is %i pixel high. It's supposed to be 200px" % h)
           return picture
    
    class MyAdmin(admin.ModelAdmin):
        form = myForm
    
    admin.site.register(Example, MyAdmin)
    
        2
  •  4
  •   M.javid munsu    7 年前

    在模型文件中使用此函数,

    from django.core.exceptions import ValidationError
    
    def validate_image(fieldfile_obj):
        filesize = fieldfile_obj.file.size
        megabyte_limit = 2.0
        if filesize > megabyte_limit*1024*1024:
            raise ValidationError("Max file size is %sMB" % str(megabyte_limit))
    
    class Company(models.Model):
        logo = models.ImageField("Logo", upload_to=upload_logo_to,validators=[validate_image], blank=True, null=True,help_text='Maximum file size allowed is 2Mb')
    
        3
  •  0
  •   Azmol    6 年前

    更新上述答案的Models.py版本

    from django.core.exceptions import ValidationError
    from django.core.files.images import get_image_dimensions
    
    class Model(models.Model):
     photo = models.ImageField()
    
     def clean(self):
    
        if not self.photo:
            raise ValidationError("No image!")
        else:
            w, h = get_image_dimensions(self.photo)
            if w != 200:
                raise ValidationError("The image is %i pixel wide. It's supposed to be 200px" % w)
            if h != 200:
                raise ValidationError("The image is %i pixel high. It's supposed to be 200px" % h)
    
        4
  •  -1
  •   Community Mohan Dere    9 年前

    Using jQuery, Restricting File Size Before Uploading

    我认为没有办法按你想要的方式去做。Agos解决方案是一条路要走。。。

    编辑:

    推荐文章