makeabilitylab / makeabilitylabwebsite

The Makeability Lab website
https://makeabilitylab.cs.washington.edu
MIT License
9 stars 65 forks source link

Admin Interface: Validate Filetypes on Upload #6

Open jonfroehlich opened 8 years ago

jonfroehlich commented 8 years ago

Do we want to validate filetypes like PDFs on upload?

Evidently, to do this, can use something called python-magic which examines a file and infers what type it is. See:

jonfroehlich commented 8 years ago

@lstearns86 This is relevant to you now that you're working on the publications page.

jonfroehlich commented 1 year ago

From chat.bing.com:

You can add a clean method to your form or model to validate that the uploaded file is a video. Here's an example of how you can do it:

from django.core.exceptions import ValidationError

def validate_video_file(value):
    import magic
    file_type = magic.from_buffer(value.read(1024), mime=True)
    if not file_type.startswith('video'):
        raise ValidationError("Files must be a video.")

class MyModel(models.Model):
    video = models.FileField(upload_to='videos/', validators=[validate_video_file])

In this example, the validate_video_file function uses the python-magic library to check the MIME type of the uploaded file. If the MIME type does not start with 'video', a ValidationError is raised.

Please note that you'll need to install the python-magic library. You can install it with pip:

pip install python-magic

Remember, this is just a basic validation. Depending on your requirements, you might want to add more sophisticated validation like checking the video duration, dimensions, etc.

It can also do PDF and image validation:

Yes, the python-magic library can also be used to validate image and PDF files. You would just need to adjust the validate_video_file function to check for the appropriate MIME types. Here's an example:

from django.core.exceptions import ValidationError

def validate_file(value):
    import magic
    file_type = magic.from_buffer(value.read(1024), mime=True)
    if not file_type.startswith(('application/pdf', 'image')):
        raise ValidationError("Files must be a PDF or an image.")

class MyModel(models.Model):
    file = models.FileField(upload_to='files/', validators=[validate_file])

In this example, the validate_file function checks if the MIME type of the uploaded file starts with 'application/pdf' (for PDF files) or 'image' (for image files). If not, a ValidationError is raised.

Please note that this is a basic validation and might not cover all possible image and PDF MIME types. Depending on your requirements, you might want to add more specific MIME type checks. For example, if you only want to allow JPEG images, you could check for 'image/jpeg' instead of 'image'. Similarly, for PDFs, you could check for 'application/pdf'.