django - 在django中,models.ImageField默认采用哪种格式

标签 django django-models

我想在 imagefield 上上传扩展名有限的文件。那么,如何仅验证 jpg、bmp 和 gif 的图像字段。
另外,默认情况下图像字段采用哪个扩展名?

最佳答案

这就是我的做法:

from django.utils.image import Image

# settings.py
# ALLOWED_UPLOAD_IMAGES = ('gif', 'bmp', 'jpeg')


class ImageForm(forms.Form):

    image = forms.ImageField()

    def clean_image(self):
        image = self.cleaned_data["image"]
        # This won't raise an exception since it was validated by ImageField.
        im = Image.open(image)

        if im.format.lower() not in settings.ALLOWED_UPLOAD_IMAGES:
            raise forms.ValidationError(_("Unsupported file format. Supported formats are %s."
                                          % ", ".join(settings.ALLOWED_UPLOAD_IMAGES)))

        image.seek(0)
        return image

也适用于 ModelForm。

单元测试:
from StringIO import StringIO

from django.core.files.uploadedfile import SimpleUploadedFile
from django.test.utils import override_settings
from django.test import TestCase


class ImageFormTest(TestCase):

    def test_image_upload(self):
        """
        Image upload
        """
        content = 'GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00' \
                  '\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;'
        image = StringIO(content)
        image.name = 'image.gif'
        image.content_type = 'image/gif'
        files = {'image': SimpleUploadedFile(image.name, image.read()), }

        form = ImageForm(data={}, files=files)
        self.assertTrue(form.is_valid())


    @override_settings(ALLOWED_UPLOAD_IMAGES=['png', ])
    def test_image_upload_not_allowed_format(self):
        image = StringIO('GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00'
                         '\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
        image.name = 'image'
        files = {'image': SimpleUploadedFile(image.name, image.read()), }
        form = ImageForm(data={}, files=files)
        self.assertFalse(form.is_valid())

枕头会允许一堆image formats

关于django - 在django中,models.ImageField默认采用哪种格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22535240/

相关文章:

python - django 的新手 : Having a bug when creating models

django - django 模型是否提供类似于表单的 clean_<fieldname>() 的东西?

django - 使用 Django QuerySet 分块处理数据库的最佳方法?

python - 如何在不使用 for 循环的情况下注释/聚合列表中的每个项目 (Django)

Django-Postgres : length of CharField as primary key

python - 在 django admin 的 list_editable 中实现一对多编辑的直接方法是什么?

Django:实例在多对多关系之前需要有一个主键值

django - 如何在django中将文件路径转换为url

django - 如何获取 Django 响应对象的内容长度?

django - 在 Django 中,你能自动映射 URL 以查看方法吗?