How does one use magic to verify file type in a Django form clean method?

后端 未结 5 686
陌清茗
陌清茗 2021-01-13 14:00

I have written an email form class in Django with a FileField. I want to check the uploaded file for its type via checking its mimetype. Subsequently, I want to limit file t

5条回答
  •  既然无缘
    2021-01-13 14:16

    In case you're handling a file upload and concerned only about images, Django will set content_type for you (or rather for itself?):

    from django.forms import ModelForm
    from django.core.files import File
    from django.db import models
    class MyPhoto(models.Model):
        photo = models.ImageField(upload_to=photo_upload_to, max_length=1000)
    class MyForm(ModelForm):
        class Meta:
            model = MyPhoto
            fields = ['photo']
    photo = MyPhoto.objects.first()
    photo = File(open('1.jpeg', 'rb'))
    form = MyForm(files={'photo': photo})
    if form.is_valid():
        print(form.instance.photo.file.content_type)
    

    It doesn't rely on content type provided by the user. But django.db.models.fields.files.FieldFile.file is an undocumented property.

    Actually, initially content_type is set from the request, but when the form gets validated, the value is updated.

    Regarding non-images, doing request.FILES['name'].read() seems okay to me. First, that's what Django does. Second, files larger than 2.5 Mb by default are stored on a disk. So let me point you at the other answer here.


    For the curious, here's the stack trace that leads to updating content_type:

    django.forms.forms.BaseForm.is_valid: self.errors
    django.forms.forms.BaseForm.errors: self.full_clean()
    django.forms.forms.BaseForm.full_clean: self._clean_fields()
    django.forms.forms.BaseForm._clean_fiels: field.clean()
    django.forms.fields.FileField.clean: super().clean()
    django.forms.fields.Field.clean: self.to_python()
    django.forms.fields.ImageField.to_python

提交回复
热议问题