Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend image field to allow pdf ( django )

I have ImageField in my form. As i discovered it uses pillow to validate that file is actually an image. This part is great, but i need to allow pdf in this form field also.

So it should check that file is image and, if not, check if it is a pdf, and then load and store.

It's great if pdf check can be really checking file format, but just extension checking is enough too.

like image 251
Yegor Razumovsky Avatar asked Feb 17 '16 19:02

Yegor Razumovsky


1 Answers

You can't do it if you're using forms.ImageField in your form. You'll need to use forms.FileField because ImageField only validates images and raises ValidationError if the file is not an image.

Here's an example:

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

Although the above code verifies the validity of images correctly (by calling ImageField.to_python() method) but to determine if the file is PDF or not, it only checks the file extension. To actually verify if the PDF is valid or not, you can try solutions on this question: Check whether a PDF-File is valid (Python). This approach tries to read the whole file in memory and if the file is too large, it might eat up your server's memory.

like image 137
xyres Avatar answered Nov 03 '22 09:11

xyres