[英]Extend image field to allow pdf ( django )
我的表单中有ImageField。 正如我发现的那样,它使用枕头来验证该文件实际上是图像。 这部分很棒,但我也需要在此表单字段中允许使用pdf。
因此,应检查文件是否为图像,如果不是,请检查文件是否为pdf,然后加载并存储。
如果pdf检查可以真正检查文件格式,那就太好了,但仅扩展名检查就足够了。
如果您在表单中使用forms.ImageField
,则无法执行此操作。 你需要使用forms.FileField
因为ImageField
唯一验证图像,并提出ValidationError
如果文件不是图像。
这是一个例子:
models.py
class MyModel(models.Model):
image = models.ImageField(upload_to='images')
表格
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是否有效,您可以尝试以下问题的解决方案: 检查PDF文件是否有效(Python) 。 这种方法尝试读取内存中的整个文件,如果文件太大,则可能会耗尽服务器的内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.