Advertisement
mickymiseck

FileCustomField

Dec 7th, 2011
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.29 KB | None | 0 0
  1. from django.db import models
  2. from django.forms import forms
  3. from django.template.defaultfilters import filesizeformat
  4. from django.utils.translation import ugettext_lazy as _
  5. from widgets import CustomFileFieldWidget
  6.  
  7. class ContentTypeRestrictedFileField(models.FileField):
  8.  
  9.     widget = CustomFileFieldWidget(attrs={'accept':"txt|pdf",})
  10.  
  11.     def __init__(self, *args, **kwargs):
  12.         self.content_types = kwargs.pop("content_types")
  13.         self.max_upload_size = kwargs.pop("max_upload_size")
  14.         print self.widget.render('o','XD')
  15.         super(ContentTypeRestrictedFileField, self).__init__(*args, **kwargs)
  16.  
  17.     def clean(self, *args, **kwargs):        
  18.         data = super(ContentTypeRestrictedFileField, self).clean(*args, **kwargs)
  19.         file = data.file
  20.         try:
  21.             content_type = file.content_type
  22.             if content_type in self.content_types:
  23.                 if file._size > self.max_upload_size:
  24.                     raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(self.max_upload_size), filesizeformat(file._size)))
  25.             else:
  26.                 raise forms.ValidationError(_('Filetype not supported.'))
  27.         except AttributeError:
  28.             pass        
  29.            
  30.         return data
  31.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement