Django file size & content_type restriction at form level vs model?
<p>I am trying to implement file size &amp; content_type restriction for my django file uploads. Ideally,i would like to validate before i upload. Initially i am using this reproduced code but it is not working.</p>

<pre><code>class ContentTypeRestrictedFileField(FileField):
"""
Same as FileField, but you can specify:
    * content_types - list containing allowed content_types. Example: ['application/pdf', 'image/jpeg']
    * max_upload_size - a number indicating the maximum file size allowed for upload.
        2.5MB - 2621440
        5MB - 5242880
        10MB - 10485760
        20MB - 20971520
        50MB - 5242880
        100MB 104857600
        250MB - 214958080
        500MB - 429916160
"""
def __init__(self, *args, **kwargs):
    self.content_types = kwargs.pop("content_types", None)
    self.max_upload_size = kwargs.pop("max_upload_size", None)
    super(ContentTypeRestrictedFileField, self).__init__(*args, **kwargs)

def clean(self, *args, **kwargs):        
    data = super(ContentTypeRestrictedFileField, self).clean(*args, **kwargs)

    file = data.file
    try:
        content_type = file.content_type
        if content_type in self.content_types:
            if file._size &gt; self.max_upload_size:
                raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(self.max_upload_size), filesizeformat(file._size)))
        else:
            raise forms.ValidationError(_('Filetype not supported.'))
    except AttributeError:
        pass        

    return data
</code></pre>

<p>So far it does not work at all. It is like i am just using a regular FileField.
However, if i do it in the views i can get it to work at form level i.e:</p>

<pre><code>if form.is_valid():
        file_name = request.FILES['pdf_file'].name

        size = request.FILES['pdf_file'].size
        content = request.FILES['pdf_file'].content_type
        ### Validate Size &amp; ConTent here

        new_pdf = PdfFiles(pdf_file = request.FILES['pdf_file'])
        new_pdf.save()
</code></pre>

<p>What is the most preferred way of doing this?</p>