Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #format_checker.py
- from django.db.models import FileField
- from django.forms import forms
- from django.template.defaultfilters import filesizeformat
- from django.utils.translation import ugettext_lazy as _
- 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", "2621440")
- 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 > 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
- #models.py
- from PIL import Image
- class Menu(models.Model):
- name = models.CharField(max_length=100)
- price = models.IntegerField()
- image = ContentTypeRestrictedFileField(
- upload_to='menu/image/',
- content_types=[[
- 'image/jpeg',
- 'image/jpg',
- 'image/png'
- ]
- ],
- max_upload_size=2621440,
- blank=True,
- null=True,
- help_text="Max size is 2.5MB"
- )
- note = models.TextField(blank=True)
- objects = models.Manager()
- def __str__(self):
- return '{0}: {1}'.format(self.kelurahan.name, self.name)
- def save(self, *args, **kwargs):
- image = Image.open(self.image)
- image_ext = os.path.splitext(self.image.path)[1][1:]
- image = image.resize((240, 480), Image.ANTIALIAS)
- self.image = image
- super(Menu, self).save(*args, **kwargs)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement