【问题标题】:Extend image field to allow pdf ( django )扩展图像字段以允许 pdf ( django )
【发布时间】:2016-05-29 16:44:13
【问题描述】:

我的表单中有 ImageField。正如我发现它使用枕头来验证该文件实际上是一个图像。这部分很棒,但我也需要在这个表单字段中允许 pdf。

所以它应该检查文件是图像,如果不是,检查它是否是pdf,然后加载和存储。

如果pdf检查真的可以检查文件格式,那就太好了,但扩展检查也足够了。

【问题讨论】:

  • 我不想切换到 mime 类型检查。我想以最少的更改扩展现有功能

标签: python django file-upload django-forms


【解决方案1】:

如果您在表单中使用forms.ImageField,则无法执行此操作。您需要使用forms.FileField,因为ImageField 仅验证图像并在文件不是图像时引发ValidationError

这是一个例子:

models.py

class MyModel(models.Model):
    image = models.ImageField(upload_to='images')

forms.py

import os
from django import forms
from .models import MyModel

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ['image']

    image = forms.FileField()

    def clean_image(self):
        uploaded_file = self.cleaned_data['image']
        try:
            # create an ImageField instance
            im = forms.ImageField()
            # now check if the file is a valid image
            im.to_python(uploaded_file)
        except forms.ValidationError:
            # file is not a valid image;
            # so check if it's a pdf
            name, ext = os.path.splitext(uploaded_file.name)
            if ext not in ['.pdf', '.PDF']:
                raise forms.ValidationError("Only images and PDF files allowed")
        return uploaded_file

虽然上面的代码正确地验证了图像的有效性(通过调用ImageField.to_python()方法),但是要确定文件是否为PDF,它只检查文件扩展名。要实际验证 PDF 是否有效,您可以尝试解决此问题:Check whether a PDF-File is valid (Python)。这种方法会尝试读取内存中的整个文件,如果文件太大,可能会占用服务器的内存。

【讨论】:

    猜你喜欢
    • 2013-04-22
    • 1970-01-01
    • 2019-06-11
    • 2018-04-02
    • 2016-12-19
    • 1970-01-01
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多