自定义的文件上传字段 服务器端验证器

root
abc abc
  • 20 Jul

def clean_articlephoto(self):
print("clean.. articlephoto......")
image = self.cleaned_data.get('articlephoto')
if not image:
return image

    # 检查文件类型,例如只允许 jpg, jpeg, png
    valid_types = ['image/jpeg', 'image/png','image/webp']
    if image.content_type not in valid_types:
        raise forms.ValidationError("只接受 JPEG 或 PNG 格式的图片。")

    # 检查文件大小,例如最大 2MB
    max_size = 2 * 1024   # 2MB in bytes
    if image.size > max_size:
        raise forms.ValidationError("文件大小不能超过 2MB。")

    return image