开发者

How to test whether a Django FileField is blank?

开发者 https://www.devze.com 2023-01-21 12:29 出处:网络
What is the right way to test whether a Django FileField is blank, i.e., when no file has been uploaded?

What is the right way to test whether a Django FileField is blank, i.e., when no file has been uploaded?

It looks like the name attribute is u'' w开发者_开发百科hen the field is blank, but I don't know whether that is reliable.


I ran in a similar problem and found a possible solution (surely not the best). I'm currently checking if the the cleaned data inside the file field is an instance of the class TemporaryUploadedFile (django.core.files.uploadedfile.TemporaryUploadedFile):

** your code here**

from django.core.files.uploadedfile import TemporaryUploadedFile

** your code here**

if isinstance(form_instance.cleaned_data['my_file'], TemporaryUploadedFile): # do stuff

I hope this is going to help.

Cheers! David


This is one from python idioms, always test it in simplest way possible:

if some_object.file:
    # File exists!
    # This of course does not guarantees that file exists on disk, or that it is 
    # readable.
else:
    # No file.
0

精彩评论

暂无评论...
验证码 换一张
取 消