Last active
July 1, 2017 08:18
-
-
Save solanoize/66861443805d5886b32fc65be7d2cc97 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 ImageFieldRestrict(FileField): | |
| def __init__(self, *args, **kwargs): | |
| self.content_types = ['image/jpeg', 'image/gif'] | |
| self.max_upload_size = 2242880 | |
| super(ImageFieldRestrict, self).__init__(*args, **kwargs) | |
| def clean(self, *args, **kwargs): | |
| data = super(ImageFieldRestrict, 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: | |
| message = 'Please keep filesize under {}. Current file size %s' | |
| message = message.format(filesizeformat(self.max_upload_size), filesizeformat(file._size)) | |
| raise forms.ValidationError(_(message)) | |
| else: | |
| raise forms.ValidationError(_('Filetype not supported.')) | |
| except AttributeError: | |
| pass | |
| return data |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from .fields import ImageFieldRestrict | |
| class Photo(models.Model): | |
| user = models.ForeignKey('auth.User', related_name="user_photos") | |
| booklet = models.ForeignKey(Booklet, related_name="photos") | |
| about = models.CharField(max_length=100) | |
| pic = ImageFieldRestrict(upload_to='photo/%Y/%m/%d') | |
| created = models.DateTimeField(auto_now_add=True) | |
| def __str__(self): | |
| return self.booklet.title | |
| class Meta: | |
| ordering = ('-created',) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment