class Attraction(models.Model): """Shared properties of destinations and events. Note: for destination field to appear in admin interface, must also be defined on `fields` in `admin.py`. """ class Meta: abstract = True name = models.CharField(max_length=50) website_url = models.URLField(blank=True, null=True) description = RichTextField() image_raw = ImageCropField(upload_to=generate_filename, verbose_name='image file', help_text=settings.IMAGE_CROPPER_HELP_TEXT) wide_image_raw = ImageCropField(upload_to=generate_filename, verbose_name='wide image file', help_text=settings.IMAGE_CROPPER_HELP_TEXT) image = ImageRatioField( 'image_raw', NARROW_IMAGE_DIMENSION_STRING, help_text='The small image. Will be displayed at ' + NARROW_IMAGE_DIMENSION_STRING) wide_image = ImageRatioField( 'wide_image_raw', WIDE_IMAGE_DIMENSION_STRING, help_text='The large image. Will be displayed at ' + WIDE_IMAGE_DIMENSION_STRING) published = models.BooleanField(default=False) priority = models.IntegerField(default=9999, null=False) accessible = models.BooleanField(default=False, help_text='Is it ADA accessible?') activities = models.ManyToManyField('Activity', blank=True) # support filtering user flags by attraction user_flags = GenericRelation(UserFlag, related_query_name='flag_attraction') def get_image_as_list(self): return list(map(int, self.image.split(','))) if self.image else [] def get_wide_image_as_list(self): return list(map( int, self.wide_image.split(','))) if self.wide_image else [] @property def is_event(self): """Helper to check which sub-class this Attraction belongs to.""" return isinstance(self, Event) @property def is_tour(self): return False def has_activity(self, activity_name): """Helper to check if an activity of a given name is available at a destination.""" return self.activities.filter(name=activity_name).exists()
class Article(models.Model): class ArticleTypes(object): community_profile = 'prof' tips_and_tricks = 'tips' CHOICES = ( (community_profile, 'Community Profile'), (tips_and_tricks, 'Tips and Tricks'), ) title = models.CharField(max_length=80) slug = models.SlugField() author = models.ForeignKey(User, on_delete=models.CASCADE) teaser = RichTextField(config_name='teaser') # above the fold content = RichTextField(null=True, blank=True) # below the fold publish_date = models.DateTimeField(blank=True, null=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) content_type = models.CharField(max_length=4, choices=ArticleTypes.CHOICES) wide_image_raw = ImageCropField(upload_to=generate_filename, null=True, verbose_name='wide image file', help_text=settings.IMAGE_CROPPER_HELP_TEXT) wide_image = ImageRatioField( 'wide_image_raw', ARTICLE_WIDE_IMAGE_DIMENSION_STRING, help_text='The large image. Will be displayed at ' + ARTICLE_WIDE_IMAGE_DIMENSION_STRING) narrow_image_raw = ImageCropField( upload_to=generate_filename, null=True, verbose_name='narrow image file', help_text=settings.IMAGE_CROPPER_HELP_TEXT) narrow_image = ImageRatioField( 'narrow_image_raw', ARTICLE_NARROW_IMAGE_DIMENSION_STRING, help_text='The small image. Will be displayed at ' + ARTICLE_NARROW_IMAGE_DIMENSION_STRING) @property def published(self): """Helper property to easily determine if an article is published""" if self.publish_date: return (self.publish_date < now()) else: return False # Managers objects = ArticleManager() profiles = CommunityProfileManager() tips = TipsAndTricksManager() def __str__(self): return self.title
class AbstractImage(TimeStampedModel): image = ImageCropField(_("Image"), blank=True, upload_to="media") list_page_cropping = ImageRatioField("image", "600x400") detail_page_cropping = ImageRatioField("image", "800x800") class Meta: abstract = True
class Teacher(ImageMixin, BaseModel): """Преподаватель""" title = models.CharField(_('Имя'), max_length=255, db_index=True) image = ImageCropField(_('Аватар'), max_length=254, blank=True, null=True, upload_to='teachers') image_thumb = ImageRatioField('image', '200x200', free_crop=True, verbose_name=_('Эскиз')) courses = models.ManyToManyField('Course', verbose_name=_('Курсы'), through='CourseTeacher', blank=True) translation_fields = ('title', ) class Meta: verbose_name = _('Преподаватель') verbose_name_plural = _('Преподаватели') def __str__(self): return self.title
class Video(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=150, blank=True) description = models.TextField(blank=True) yt_id = models.TextField(max_length=20, blank=True) yt_title = models.CharField(max_length=300, blank=True) published_at_yt = models.DateTimeField(null=True) date_created = models.DateTimeField(default=timezone.now) thumbnail = ImageCropField(upload_to=get_thumbnail_path, blank=True, default='logodefault.png') thumbnail_ratio = ImageRatioField('thumbnail', '1600x900') yt_lesson_number = models.CharField(max_length=4, blank=True) professor = models.ForeignKey('categories.Professor', related_name='videos', null=True, blank=True, default=None) def __unicode__(self): return self.title class Meta: ordering = [ 'title', ]
class ProductImage(ImageMixin, BaseModel): """Изображения продукта""" product = models.ForeignKey(Product, verbose_name=_('Продукт'), related_name='images') image = ImageCropField(_('Изображение'), max_length=255, upload_to='products/images') thumb_images = ImageRatioField('image', size='800x600', verbose_name=_('Обрезка полей'), allow_fullsize=True, free_crop=True) alt = models.CharField( _('Подпись (alt)'), max_length=255, blank=True, null=True, help_text=_('Альтернативный текст вместо изображения')) translation_fields = ('alt', ) def __str__(self): return str(self.pk) class Meta: verbose_name = _('Изображение продукта') verbose_name_plural = _('Изображения продукта')
class StudyMedia(models.Model): title = models.CharField(max_length=120) description = BBCodeField(blank=True) type = models.ForeignKey(StudyMediaType, null=True, on_delete=models.SET_NULL) tags = models.ManyToManyField(Tag, blank=True, through='StudyMediaTags') image = ImageCropField(upload_to='resources/%Y/%m/%d/') image_crop = ImageRatioField('image', '684x320') guide_text = BBCodeField(blank=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('resources_detail', args=[self.id]) @property def visible_tags(self): return self.tags.filter(studymediatags__validity__gte=random.random()) @property def rating(self): avg = self.studymediareview_set.all().aggregate( models.Avg('recommend')) return round(avg['recommend__avg'] * 5) @property def has_rating(self): return len(self.studymediareview_set.all()) > 0
class Marca(models.Model): """ Es el marca comercial de un producto. Ejemplo: Rosamonte """ fabricante = models.ForeignKey('EmpresaFabricante', null=True, blank=True) nombre = models.CharField(max_length=100, unique=True, verbose_name=u"Nombre de la marca") logo = ImageCropField(null=True, blank=True, upload_to='marcas') # size is "width x height" logo_cropped = ImageRatioField('logo', '150x125', verbose_name=u'Recortar logo', free_crop=True) logo_changed = MonitorField(monitor='logo', editable=False) def __unicode__(self): return self.nombre class Meta: unique_together = (('nombre', 'fabricante')) verbose_name = u"marca" verbose_name_plural = u"marcas"
class Ambassadors(models.Model): name = models.CharField(max_length=255) position = models.CharField(max_length=255) original_image_width = models.PositiveIntegerField(null=True) original_image_height = models.PositiveIntegerField(null=True) thumb_image_width = models.PositiveIntegerField(null=True) thumb_image_height = models.PositiveIntegerField(null=True) image = ImageCropField(upload_to='uploaded_images') min_free_cropping = ImageRatioField('image', free_crop=True) link = models.CharField(max_length=255) order = models.PositiveIntegerField(null=True) def get_thumb_max_size(self): return str(self.thumb_image_width) + 'x' + str(self.thumb_image_height) def save(self, *args, **kwargs): found_id = self.id super(Ambassadors, self).save(*args, **kwargs) if self.image and found_id is None and self.original_image_width and self.original_image_height: print '123' self.image = get_thumbnailer(self.image).get_thumbnail({ 'size': (self.original_image_width, self.original_image_height), }).name super(Ambassadors, self).save(*args, **kwargs) class Meta: ordering = ('name', ) verbose_name_plural = u'COS Ambassadors'
class CarouselEntry(TranslatableModel): translations = TranslatedFields( text_over_image=models.CharField(_('image text'), max_length=255), navigation_entry=models.CharField(_('navigation entry'), max_length=30), ) image = ImageCropField(_('image'), upload_to='carousel') cropped = ImageRatioField('image', '{0}x{1}'.format(IMAGE_WIDTH, IMAGE_HEIGHT), size_warning=True) order = models.PositiveIntegerField(unique=True) text_background_color = ColorPickerField(blank=True) objects = CarouselEntryManager() def __unicode__(self): return self.navigation_entry_translated() def text_over_image_translated(self): try: return self.text_over_image except: return self.translations.all()[0].text_over_image text_over_image_translated.short_description = 'Image Text' def navigation_entry_translated(self): try: return self.navigation_entry except: return self.translations.all()[0].navigation_entry navigation_entry_translated.short_description = 'Navigation Text' def cropped_img_url(self): return get_thumbnailer(self.image).get_thumbnail({ 'size': (IMAGE_WIDTH, IMAGE_HEIGHT), 'box': self.cropped, 'crop': True, 'detail': True, }).url def image_display_in_admin(self): return "<a href='{0}'><img src='{0}' width='{1}' height='{2}'></a>".format( self.cropped_img_url(), IMAGE_WIDTH / 3, IMAGE_HEIGHT / 3) image_display_in_admin.allow_tags = True image_display_in_admin.short_description = 'Image Preview' def carousel_entry_id(self): return 'entry{}'.format(self.order) class Meta: verbose_name_plural = _('carousel entries') ordering = ('order', )
class NewsPost(models.Model): topic = models.CharField(max_length=200, blank=True) description = models.TextField(blank=True) dateTime = models.DateTimeField('News Post Created Time') picture = ImageCropField(upload_to='codelab-images-users', blank=True) cropPicture = ImageRatioField('picture', '800x450', allow_fullsize=True) def __unicode__(self): return self.topic
class Project(models.Model): topic = models.CharField(max_length=200, blank=True) picture = ImageCropField(upload_to='codelab-images-projects', blank=True) cropPicture = ImageRatioField('picture', '1000x1000', allow_fullsize=True) dateTime = models.DateTimeField("Project Created Time") author = models.ForeignKey(User) def __unicode__(self): return self.topic
class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user ' 'can log into this admin ' 'site.')) is_active = models.BooleanField(_('active'), default=True, help_text=_('Designates whether this user' ' should be treated as ' 'active. Unselect this instead' ' of deleting accounts.')) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) avatar = ImageCropField(_('profile picture'), upload_to="avatars/", validators=[avatar_validation], null=True, blank=True) cropping = ImageRatioField( 'avatar', '70x70', help_text=_( 'Note that the preview above will only be updated after you submit the' ' form.')) objects = UserManager() USERNAME_FIELD = 'email' class Meta(AbstractBaseUser.Meta): abstract = False def __unicode__(self): return self.get_display_name() def get_full_name(self): """ Returns the first_name plus the last_name, with a space in between. """ return ' '.join([self.first_name, self.last_name]).strip() def get_short_name(self): """ Returns the short name for the user. """ return self.first_name def get_display_name(self): return self.get_full_name() or self.email def get_absolute_url(self): return reverse('users_profile', args=[str(self.pk)])
class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) description = models.CharField(blank=True, max_length=255) avatar = ImageCropField(upload_to='avatars/', blank=True) cropping = ImageRatioField('avatar', '300x400') def __str__(self): return self.user.username
class Food(models.Model): category = models.ForeignKey('Category', on_delete=models.CASCADE) name = models.CharField(null=False, blank=False, max_length=200) description = models.TextField(null=True, blank=True) price = models.DecimalField(null=False, blank=False, max_digits=6, decimal_places=2, default=0) image = ImageCropField(null=True, blank=True, upload_to='food/imgs/') thumbnail = ImageRatioField('image', '100x75') enabled = models.BooleanField(null=False, blank=False, default=True, help_text='Enable or disable this element') def __str__(self): return '<%(category)s> %(name)s' % {'name': self.name, 'category': self.category.name}
class Professor(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=40, blank=True) description = models.TextField(blank=True) profile_image = ImageCropField(upload_to=get_image_path, blank=True, default='logodefault.png') profile_ratio = ImageRatioField('profile_image', '320x320') def __unicode__(self): return self.name
class Image_Cropping(Model): image = ImageCropField( "image", blank=True, null=True, upload_to='uploaded_images', ) image_cropped = ImageRatioField( 'image', '430x360', )
class Post(models.Model): objects = models.Manager() user = models.ForeignKey(User, on_delete = models.CASCADE) content = models.TextField() image = ImageCropField(upload_to = "static/images/", blank = True) cropping = ImageRatioField('image', '300x300') mark = models.ManyToManyField(User, related_name='mark') like = models.ManyToManyField(User, related_name='like') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
class MyUser(AbstractBaseUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=255, default=generate_username, unique=True) email = models.EmailField(verbose_name='email address', max_length=255, null=True, blank=True, default='') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=80) profile_image = ImageCropField(upload_to=get_image_path, blank=True, default='profiledefault.jpg') profile_ratio = ImageRatioField('profile_image', '320x320') email_confirmed = models.BooleanField(default=False) course_hours = models.IntegerField(default=0) is_beta = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'username' def get_full_name(self): # The user is identified by their email address full_name = self.first_name full_name += ' ' full_name += self.last_name return full_name def get_short_name(self): # The user is identified by their email address return self.first_name def __unicode__(self): # __unicode__ on Python 2 return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin
class UserProfile(models.Model): user = models.ForeignKey(User) degree = models.CharField(max_length=10, blank=True) email = models.EmailField(max_length=30, blank=True) website = models.URLField(blank=True) phone = models.CharField(max_length=10, blank=True) bio = models.TextField(blank=True) picture = ImageCropField(upload_to='codelab-images-users', blank=True) cropPicture = ImageRatioField('picture', '500x500', allow_fullsize=True) def __unicode__(self): return self.user.username
class EventImage(models.Model): event = models.ForeignKey(Event, blank=False, null=False) order = models.PositiveIntegerField(default=1) picture = ImageCropField(upload_to=picture_file_path, blank=True, null=True, help_text='The event picture') cropping = ImageRatioField('picture', '180x180', size_warning=True, allow_fullsize=True)
class AbstractEmpresa(models.Model): nombre = models.CharField(max_length=100, unique=True) logo = ImageCropField(null=True, blank=True, upload_to='empresas') logo_cropped = ImageRatioField('logo', '150x125', verbose_name=u'Recortar logo', free_crop=True) logo_changed = MonitorField(monitor='logo', editable=False) def __unicode__(self): return self.nombre class Meta: abstract = True
class Image_Cropping_Autocomplete_Light(Model): text = CharField(max_length=255) image = ImageCropField( "image", blank=True, null=True, upload_to='uploaded_images', ) image_cropped = ImageRatioField( 'image', '430x360', ) def __str__(self): return self.text
class Team(models.Model): name = models.CharField(max_length=255, unique=True) position = models.CharField(max_length=255) alumni = models.BooleanField(default=False) original_image_width = models.PositiveIntegerField(null=True) original_image_height = models.PositiveIntegerField(null=True) thumb_image_width = models.PositiveIntegerField(null=True) thumb_image_height = models.PositiveIntegerField(null=True) image = ImageCropField(upload_to='uploaded_images') mini_image = ImageRatioField('image', free_crop=True) email = models.CharField(max_length=255, null=True, blank=True) yahoo = models.CharField(max_length=255, null=True, blank=True) picasa = models.CharField(max_length=255, null=True, blank=True) youtube = models.CharField(max_length=255, null=True, blank=True) OSF_url = models.CharField(max_length=255, null=True, blank=True) pinterest = models.CharField(max_length=255, null=True, blank=True) wordpress = models.CharField(max_length=255, null=True, blank=True) tumblr_url = models.CharField(max_length=255, null=True, blank=True) google_url = models.CharField(max_length=255, null=True, blank=True) github_url = models.CharField(max_length=255, null=True, blank=True) twitter_url = models.CharField(max_length=255, null=True, blank=True) facebook_url = models.CharField(max_length=255, null=True, blank=True) linkedin_url = models.CharField(max_length=255, null=True, blank=True) personal_website = models.CharField(max_length=255, null=True, blank=True) def __unicode__(self): return self.name def get_thumb_max_size(self): return str(self.thumb_image_width) + 'x' + str(self.thumb_image_height) def save(self, *args, **kwargs): found_id = self.id super(Team, self).save(*args, **kwargs) if self.image and found_id is None and self.original_image_width and self.original_image_height: self.image = get_thumbnailer(self.image).get_thumbnail({ 'size': (self.original_image_width, self.original_image_height), }).name super(Team, self).save(*args, **kwargs) class Meta: ordering = ('name', ) verbose_name_plural = u'Add COS Team Images Here' verbose_name = u'COS'
class Customer(models.Model): name = models.CharField(_('Customer'), max_length=200) information = models.TextField() email = models.EmailField() image = ImageCropField(upload_to='media/customers', blank=True) cropping = ImageRatioField('image', '430x360') color = models.CharField(max_length=10) date = models.DateField() time = models.TimeField() datetime = models.DateTimeField() class Meta: ordering = ('pk', ) permissions = (("view_customer", "Can see available customers"), )
class Person(models.Model): name = models.CharField(_('Name'), max_length=50) image = ImageCropField(_('Picture'), upload_to='person/') visible = models.BooleanField(_('Visible'), default=True) event = models.ForeignKey('Event', null=False) image_crop = ImageRatioField('image', '300x300') # TODO: Define these sizes def __str__(self): return self.name class Meta: ordering = ['event', 'name'] verbose_name = _('Person') verbose_name_plural = _('People')
class Blog(models.Model): def path_upload(self, filename): return f'media/blog/Blog/{self.id_blog}/images/image.jpg' def get_id(self, allObject, id): allId = allObject.values_list('id_blog', flat=True) while id in allId: id = f'blg{str(uuid4().int)[:8]}' return id id_blog = models.CharField(max_length=11, primary_key=True) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) cover = ImageCropField(upload_to=path_upload) cropping = ImageRatioField('cover', '1900x1267') title = models.CharField(max_length=50) content = models.TextField() is_show = models.BooleanField(default=False) slug = models.SlugField(blank=True) timeCreate = models.DateTimeField(auto_now_add=True) timeUpdate = models.DateTimeField(auto_now=True) def save(self): allBlog = Blog.objects.all() path = [ f'media/blog/Blog/{self.id_blog}/images/image.jpg', f'media/blog/Blog/{self.id_blog}/images/image.jpg.300x300_q85_detail_upscale.jpg' ] if self.id_blog == '' or self.id_blog == None: id = f'blg{str(uuid4().int)[:8]}' self.id_blog = self.get_id(allBlog, id) else: original_image = Image.open(os.path.join(BASE_DIR, path[0])) cord = str(self.cropping).split(',') image_cropped = original_image.crop((int(cord[0]), int(cord[1]), int(cord[2]), int(cord[3]))) default_storage.delete(path[0]) image_cropped.save(os.path.join(BASE_DIR, path[0])) self.slug = slugify(self.title) default_storage.delete(path[1]) super(Blog, self).save() def __str__(self): return f'{self.user.username} | {self.title}'
class Image(models.Model): image = ImageCropField(upload_to='images_thumbnails', verbose_name=_('Image'), blank=True, null=True) cropping = ImageRatioField( 'image', '700x450', size_warning=True, verbose_name=_('Cropping'), help_text=_('The image must be 700x450 px. You can crop it here.')) def __unicode__(self): return self.image.name class Meta(object): verbose_name = _('Image') verbose_name_plural = _('Images')
class CropImageExample(models.Model): name = models.CharField(max_length=255, unique=True) position = models.CharField(max_length=255) original_image_width = models.PositiveIntegerField(null=True) original_image_height = models.PositiveIntegerField(null=True) thumb_image_width = models.PositiveIntegerField(null=True) thumb_image_height = models.PositiveIntegerField(null=True) image = ImageCropField(upload_to='uploaded_images') min_free_cropping = ImageRatioField('image', free_crop=True) facebook_url = models.CharField(max_length=255, null=True, blank=True) twitter_url = models.CharField(max_length=255, null=True, blank=True) tumblr_url = models.CharField(max_length=255, null=True, blank=True) github_url = models.CharField(max_length=255, null=True, blank=True) google_url = models.CharField(max_length=255, null=True, blank=True) OSF_url = models.CharField(max_length=255, null=True, blank=True) linkedin_url = models.CharField(max_length=255, null=True, blank=True) personal_Email = models.CharField(max_length=255, null=True, blank=True) personal_web = models.CharField(max_length=255, null=True, blank=True) def __unicode__(self): return self.name def get_thumb_max_size(self): return str(self.thumb_image_width) + 'x' + str(self.thumb_image_height) def save(self, *args, **kwargs): found_id = self.id super(CropImageExample, self).save(*args, **kwargs) if self.image and found_id is None and self.original_image_width and self.original_image_height: print '123' self.image = get_thumbnailer(self.image).get_thumbnail({ 'size': (self.original_image_width, self.original_image_height), }).name super(CropImageExample, self).save(*args, **kwargs) class Meta: ordering = ('name', ) verbose_name_plural = u'Add COS Team Images Here'
class ExtraImage(models.Model): class Meta: abstract = True image_raw = ImageCropField(upload_to=generate_filename, null=False, verbose_name='image file', help_text=settings.IMAGE_CROPPER_HELP_TEXT) image = ImageRatioField('image_raw', NARROW_IMAGE_DIMENSION_STRING, help_text='Image will be displayed at ' + NARROW_IMAGE_DIMENSION_STRING) wide_image = ImageRatioField('image_raw', WIDE_IMAGE_DIMENSION_STRING, help_text='Image will be displayed at ' + WIDE_IMAGE_DIMENSION_STRING) def __str__(self): return self.image_raw.url if self.image_raw else ''