class Product(models.Model): name = models.CharField(max_length=250, default='') image = ImageCropField(upload_to='product', null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True) subcategory = models.ForeignKey(SubCategory, on_delete=models.SET_NULL, null=True, blank=True) cropping = ImageRatioField('image', '100x100') @property def image_tag(self): try: return mark_safe('<img src="%s" />' % self.image.url) except: return 'None' @property def get_small_image(self): return mark_safe('<img src="%s" />' % self.get_small_image_url) @property def get_small_image_url(self): return BASE_URL + get_thumbnailer(self.image).get_thumbnail({ 'size': (100, 100), 'box': self.cropping, 'crop': 'smart', }).url def __str__(self): return '%s (%s)' % (self.name, self.category) class Meta: verbose_name = 'Product' verbose_name_plural = 'Products'
class Quiz(models.Model): """ Master Model which holds all the components. Quiz classes store publishing information, basic details and relationships with question objects. """ headline = models.CharField('Headline', max_length=255) blurb = models.TextField('Quiz Description', null=True, blank=True) published = models.BooleanField('Published') pub_date = models.DateTimeField('Publish Date/Time') questions = models.ManyToManyField('Question', null=True, blank=True) quiz_photo = ImageCropField('Art', upload_to=uploadQuizzoPhoto, null=True, blank=True) cropping = ImageRatioField('quiz_photo', '300x400') slug = models.SlugField('Slug') class Meta: ordering = ['-pub_date'] verbose_name_plural = 'Quizzes' get_latest_by = 'pub_date' def is_published(self): return self.published def __unicode__(self): return self.headline def get_absolute_url(self): if self.published == True: return "/webapps/quiz/%s/%s" % (str(self.id), self.slug)
class Gallery(models.Model): title = models.CharField(max_length=250, null=True, blank=True) image = ImageCropField(blank=True, null=True, upload_to='uploaded_images') cropping = ImageRatioField('image', '150x150') @property def get_small_img(self): url = get_thumbnailer(self.image).get_thumbnail({ 'size': (231, 231), 'box': self.cropping, 'crop': True, 'detail': True, }).url return url def __str__(self): thumbnail_url = get_thumbnailer(self.image).get_thumbnail({ 'size': (150, 150), 'box': self.cropping, 'crop': True, 'detail': True, }).url return mark_safe('<img width="100" src="%s" />' % thumbnail_url)
class UserProfile(User): name = models.CharField(max_length=250, default='') phone = models.CharField(max_length=250, default='') rating = models.IntegerField(default=0) image = ImageCropField(blank=True, upload_to='user_photo') cropping = ImageRatioField('image', '60x60') @property def get_small_image(self): return mark_safe('<img src="%s" />' % self.get_small_image_url) @property def get_small_image_url(self): try: return BACKEND_URL + get_thumbnailer(self.image).get_thumbnail( { 'size': (60, 60), 'box': self.cropping, 'crop': 'smart', }).url except: return BACKEND_URL + 'noimage.png' def __str__(self): return self.name class Meta: verbose_name = 'UserProfile' verbose_name_plural = 'UserProfile'
class ImageBlock(Block): image = ImageCropField(upload_to='uploads/images/%Y/%m') caption = models.CharField(max_length=255, blank=True) use_thumbnail = models.BooleanField(help_text='Crop using the thumbnail dimensions specified below, or simply crop the uploaded image.') thumbnail_dimensions = models.CharField(max_length=255, default=settings.IMAGE_CROPPING_SIZE, help_text='Maximum dimensions for cropped image.', blank=True) thumbnail = ImageRatioField('image', '0x0') # 0x0 allows users to freely transform thumbnail. def __unicode__(self): return self.image.name
class User(AbstractBaseUser): id = models.AutoField(primary_key=True, unique=True) username = models.CharField(max_length=50, unique=True, db_index=True) email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=50, db_index=True, unique=True) image = ImageCropField(upload_to='photos/', default=os.path.join('photos', '001.jpg').replace('\\', '/')) cropping = ImageRatioField('image', '200x200', allow_fullsize=True) describe = models.CharField(max_length=254, db_index=True) money = models.IntegerField(default=100) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) # Permissions can_comment = models.BooleanField(default=True) can_upload = models.BooleanField(default=True) can_bullet = models.BooleanField(default=True) follow_users = models.ManyToManyField("User", related_name="following_users") like_videos = models.ManyToManyField("Video", related_name="like_videos") collection_videos = models.ManyToManyField( "Video", related_name="collection_videos") objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def get_full_name(self): return self.name def get_short_name(self): return self.name @property def is_staff(self): return self.is_admin def __str__(self): return self.username 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 def get_absolute_url(self): return '/personal/%u' % self.pk
class Profile(models.Model): user = models.OneToOneField(BaseUser) full_name = models.CharField(blank=True, max_length=255) description = models.TextField(blank=True, null=True) social_accounts = JSONField(default=json_field_default, blank=True, null=True) works_at = models.CharField(blank=True, null=True, max_length=255) studies_at = models.CharField(blank=True, null=True, max_length=255) avatar = ImageCropField(blank=True, null=True) full_image = ImageCropField(upload_to='avatars/', blank=True, null=True) cropping = ImageRatioField('full_image', '300x300') skype = models.CharField(blank=True, null=True, max_length=255) def get_gh_profile_url(self): return self.social_accounts.get('GitHub')
class Entry(ModelWithSlug): STATUS_OPTIONS = ( (0, 'Draft'), (1, 'Published'), ) VISIBILITY_OPTIONS = ( (0, 'Public'), (1, 'Private'), ) title = models.CharField(max_length=100) slug = models.SlugField(max_length=255) publish_date = models.DateTimeField(auto_now_add=True) status = models.IntegerField(max_length=1, choices=STATUS_OPTIONS, default=0) visibility = models.IntegerField(max_length=1, choices=VISIBILITY_OPTIONS, default=0) body = models.TextField() excerpt = models.TextField( blank=True, help_text='A short introduction for the entry. If not supplied, \ the first paragraph of the body will be used.') category = models.ForeignKey('Category') tags = models.ManyToManyField('Tag', blank=True) user = models.ForeignKey(User) image = ImageCropField(upload_to='i/uploads/%Y/%m') cropping = ImageRatioField('image', settings.IMAGE_CROPPING_SIZE) caption = models.CharField(max_length=255, blank=True) objects = models.Manager() published_objects = PublishedManager() class Meta: verbose_name_plural = "Entries" ordering = ['-publish_date'] def __unicode__(self): return self.title @models.permalink def get_absolute_url(self): return ('blog.views.entry', (), {'slug': self.slug}) def save(self, **kwargs): unique_slugify(self, self.title) super(Entry, self).save()
class HomeImage(models.Model): image = models.ForeignKey(Image) image_field = ImageCropField(blank=True, null=True, upload_to='home_slide/') active = models.BooleanField(default=0) cropping = ImageRatioField('image_field', '625x350', size_warning=True) croppedImage = ImageField(blank=True, null=True, upload_to='home_slide/') def __unicode__(self): return self.image.collection.artist.__unicode__() def save(self, *args, **kwargs): # Get file name from image strImagePath = self.image.photo.name strImageName = strImagePath.split('/')[3] strUploadTo = 'home_slide/' strExtention = '.300x300_q85_detail.jpg' # Set image field path strDesImage = strUploadTo + strImageName self.image_field = strDesImage if(self.id is not None): homeImage = HomeImage.objects.get(pk=self.id) else: homeImage = None if(homeImage is None or homeImage.image != self.image): # Copy file into image field path im = PImage.open(settings.MEDIA_ROOT + strImagePath) im.save(settings.MEDIA_ROOT + strDesImage) # Copy image into image field path with extension for Cropping field exIm = PImage.open(settings.MEDIA_ROOT + strImagePath) exIm.save(settings.MEDIA_ROOT + strDesImage + strExtention) if(self.cropping != ''): # Crop image cropImage = PImage.open(settings.MEDIA_ROOT + strImagePath) cropP = self.cropping.split(',') box = (int(cropP[0]), int(cropP[1]), int(cropP[2]), int(cropP[3])) croppedImageName = strUploadTo + 'slide_' + str(self.image.id) + '.jpg' self.croppedImage = croppedImageName cropImage.crop(box).save(settings.MEDIA_ROOT + croppedImageName) # Resize cropped image size = 625,350 im = PImage.open(settings.MEDIA_ROOT + croppedImageName) im = im.resize(size, PImage.ANTIALIAS) im.save(settings.MEDIA_ROOT + croppedImageName) super(HomeImage, self).save(*args, **kwargs)
class UserMedia(models.Model): TYPE_MEDIA = (('photo', _('Photo')), ('video', _('Video'))) ORIENTATION = (('land', _('Landscape')), ('port', _('Portrait'))) ROLE_MEDIA = (('public', _('Public')), ('private', _('Private'))) type_media = models.CharField(verbose_name=_('Type of media'), choices=TYPE_MEDIA, default='photo', max_length=5) role_media = models.CharField(verbose_name=_('Role of media'), choices=ROLE_MEDIA, default='public', max_length=10) orient = models.CharField(verbose_name=_('Orientation'), choices=ORIENTATION, default='port', max_length=5) user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) is_main = models.BooleanField(default=False) is_approved = models.BooleanField(default=False) is_deleted = models.BooleanField(default=False) is_published = models.BooleanField(default=False) title = models.CharField(max_length=250) video = models.FileField(blank=True, upload_to='user_video') image = ImageCropField(blank=True, upload_to='user_photo') cropping = ImageRatioField('image', '80x80') @property def image_tag(self): return mark_safe('<img width="150" src="%s" />' % self.image.url) @property def get_small_image_tag(self): return mark_safe('<img src="%s" />' % self.get_small_image_url) @property def get_small_image_url(self): try: return BACKEND_URL + get_thumbnailer(self.image).get_thumbnail( { 'size': (80, 80), 'box': self.cropping, 'crop': 'smart', }).url except: return BACKEND_URL + 'noimage.png'
class Image(models.Model): image_field = ImageCropField(upload_to="image/") cropping = ImageRatioField("image_field", "120x100", allow_fullsize=True) cropping_free = ImageRatioField("image_field", "300x230", free_crop=True, size_warning=True) class Meta: app_label = "example" def get_cropping_as_list(self): if self.cropping: return list(map(int, self.cropping.split(",")))
class Image(models.Model): image_field = ImageCropField(upload_to='image/') cropping = ImageRatioField('image_field', '120x100', allow_fullsize=True) cropping_free = ImageRatioField('image_field', '300x230', free_crop=True, size_warning=True) class Meta: app_label = 'example' def get_cropping_as_list(self): if self.cropping: return list(map(int, self.cropping.split(',')))
class Maket(models.Model): title = models.CharField(verbose_name='Заголовок', max_length=250) image = ImageCropField(upload_to='files') cropping = ImageRatioField('image', '150x150') @property def small_image_url(self): try: return get_thumbnailer(self.image).get_thumbnail({ 'size': (150, 150), 'box': self.cropping, 'crop': 'smart', }).url except Exception as e: print(e) return SERVER_NAME + 'static/noimage.png'
class Maket(models.Model): title = models.CharField(verbose_name=_('Title'), max_length=250) image = ImageCropField(upload_to='files') cropping = ImageRatioField('image', '150x150') project = models.ForeignKey('project.Project', on_delete=models.CASCADE, default=1) @property def small_image_url(self): try: return get_thumbnailer(self.image).get_thumbnail({ 'size': (150, 150), 'box': self.cropping, 'crop': 'smart', }).url except Exception as e: print(e) return SERVER_NAME + 'static/noimage.png'
class File(models.Model): title = models.CharField(verbose_name=_('Title'), max_length=250, blank=True, null=True) image = ImageCropField(upload_to='files') task = models.ForeignKey( Task, verbose_name=_("Task"), on_delete=models.CASCADE) cropping = ImageRatioField('image', '80x80') @property def small_image_url(self): try: return get_thumbnailer(self.image).get_thumbnail({ 'size': (80, 80), 'box': self.cropping, 'crop': 'smart', }).url except Exception as e: return SERVER_NAME + 'static/noimage.png'
class Project(models.Model): title = models.CharField(verbose_name='Название', max_length=160, unique=True) name = models.CharField(verbose_name='Название (лат)', max_length=160, unique=True) desc = models.TextField(verbose_name='Описание') image = ImageCropField(upload_to='files') cropping = ImageRatioField('image', '150x150') git = models.CharField(verbose_name='git репозиторий', max_length=250, unique=True) git_url = models.CharField(verbose_name='url git репозитория', max_length=250, default='') release_url = models.CharField(verbose_name='url релизной версии', max_length=250, default='') media_path = models.CharField(verbose_name='Путь к медиа', max_length=250, default='') venv_path = models.CharField(verbose_name='Путь к ВО', max_length=250, default='', null=True, blank=True) def __str__(self): return self.title @property def small_image_url(self): try: return get_thumbnailer(self.image).get_thumbnail({ 'size': (80, 80), 'box': self.cropping, 'crop': 'smart', }).url except Exception as e: return '/static/noimage.png' @property def small_image_tag(self): return mark_safe(f'<img src="{self.small_image_url}">')
class Product(models.Model): name = models.CharField(max_length=250, default='') image = ImageCropField(upload_to='product', null=True, blank=True) cropping = ImageRatioField( 'image', '100x100') # поле для хранения размера обрезки изображения category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True) subcategory = models.ForeignKey(SubCategory, on_delete=models.SET_NULL, null=True, blank=True) @property def get_small_image(self): return mark_safe('<img src="%s" />' % self.get_small_image_url) @property def get_small_image_url(self): try: return BACKEND_URL + get_thumbnailer(self.image).get_thumbnail( { 'size': (100, 100), 'box': self.cropping, 'crop': 'smart', }).url except: return BAKEND_URL + "Noimage.png" def __str__(self): return '%s (%s)' % (self.name, self.category) @property def image_tag(self): try: return mark_safe('<img src="%s" />' % self.image.url) except: return 'None' class Meta: ordering = ['category']
class User(AbstractBaseUser): id = models.AutoField(primary_key=True, unique=True) username = models.CharField(max_length=50, unique=True, db_index=True) email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=50, db_index=True, unique=True) image = ImageCropField( upload_to='avatar/', default=os.path.join('', 'default.jpg').replace('\\', '/') ) cropping = ImageRatioField('image', '200x200', allow_fullsize=True) is_active = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def get_full_name(self): return self.name def get_short_name(self): return self.name @property def is_staff(self): return self.is_admin def __str__(self): return self.username 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
class Image(Orderable): gallery = models.ForeignKey(Gallery, related_name="images") title = models.CharField(_('title'), max_length=100, blank=True) caption = models.TextField(_('caption'), blank=True) image = ImageCropField(blank=True, null=True, upload_to='uploads/galleries/images/') cropping = ImageRatioField( 'image', IMAGE_CROPPING_RATIO) # size is "width x height" class Meta(Orderable.Meta): verbose_name = _('image') verbose_name_plural = _('images') def __unicode__(self): return '%s' % (self.title or self.id) @property def thumbnail(self): return thumbnail(self.image, self.cropping) @property def croppable(self): return croppable(self.image) def serialize(self): context = { 'id': self.id, 'gallery': self.gallery.id, 'title': self.title, 'caption': self.caption, 'image': self.image, 'cropping': self.cropping, 'thumbnail': self.thumbnail, 'croppable': self.croppable, 'org_width': self.image.width, 'org_height': self.image.height, 'order': self.sort_order } return context
class Professor(EscolaMixin): bibliografia = models.TextField(blank=True, default='', verbose_name=_('Bibliografia')) avatar = ImageCropField(upload_to="avatars/", verbose_name=_('Avatar'), validators=[avatar_validation], null=True, blank=True) cropping = ImageRatioField( 'avatar', '128x128', verbose_name=_('Seleção (Enquadramento)'), help_text=_('A configuração do Avatar ' 'é possível após a atualização da fotografia.')) class Meta: verbose_name = _('Professor') verbose_name_plural = _('Professores')
class TalkProposal(models.Model): level_choices = ( ('1', _('Beginner')), ('2', _('Medium')), ('3', _('Advanced')), ) title = models.CharField(_('Title'), max_length=600) type = models.ForeignKey(TalkType, verbose_name=_('Type')) long_description = models.TextField(_('Long Description')) confirmed = models.BooleanField(_('Confirmed'), default=False) dummy_talk = models.BooleanField(_('Dummy Talk?'), default=False) abstract = models.TextField( _('Abstract'), help_text=_('Short idea of the talk (Two or three sentences)')) sede = models.ForeignKey(Sede, verbose_name=_noop('Sede'), help_text=_('Sede you are proposing the talk to'), related_name='talk_proposals') speakers_names = models.CharField( _('Speakers Names'), max_length=600, help_text=_("Comma separated speaker's names")) speakers_email = models.CharField( _('Speakers Emails'), max_length=600, help_text=_("Comma separated speaker's emails")) labels = models.CharField( _('Labels'), max_length=200, help_text=_('Comma separated tags. i.e. Linux, Free Software, Debian')) presentation = models.FileField( _('Presentation'), upload_to='talks', blank=True, null=True, help_text= _('Any material you are going to use for the talk (optional, but recommended)' )) home_image = ImageCropField( upload_to='talks_thumbnails', verbose_name=_('Home Page Image'), blank=True, null=True, help_text=_( 'Image that is going to appear in the home page of this web for promoting the ' 'talk (optional)')) cropping = ImageRatioField( 'home_image', '700x450', size_warning=True, verbose_name=_('Cropping'), help_text=_('The image must be 700x450 px. You can crop it here.')) level = models.CharField(_('Level'), choices=level_choices, max_length=100, help_text=_("The talk's Technical level"), default='Beginner') def get_absolute_url(self): return "/sede/" + self.sede.url + '/talk/detail/proposal/' + str( self.id) def __unicode__(self): return self.title class Meta: verbose_name = _('Talk Proposal') verbose_name_plural = _('Talk Proposals')
class NablaUser(AbstractUser): telephone = models.CharField(verbose_name="Telefon", max_length=15, blank=True) cell_phone = models.CharField(verbose_name="Mobil", max_length=15, blank=True) birthday = models.DateField(verbose_name="Bursdag", blank=True, null=True) address = models.CharField(verbose_name="Adresse", max_length=40, blank=True) mail_number = models.CharField(verbose_name="Postnr", max_length=4, blank=True) web_page = models.CharField(verbose_name="Hjemmeside", max_length=80, blank=True) wants_email = models.BooleanField(verbose_name="Motta kullmail", default=True) about = models.TextField(verbose_name="Biografi", blank=True) avatar = ImageCropField(verbose_name="Avatar", blank=True, null=True, upload_to="avatars") cropping = ImageRatioField( # assosiated ImageField: "avatar", # Ratio and Minimum size # (width, height): "140x170", allow_fullsize=True, verbose_name="Beskjæring", size_warning=True, ) ntnu_card_number = models.CharField( verbose_name="NTNU kortnr", max_length=10, blank=True, help_text= ("Dette er et 7-10-sifret nummer på baksiden av kortet. " "På nye kort er dette sifrene etter EM. " "På gamle kort er dette sifrene nede til venstre. " "Det kan brukes of å identifisere deg på bedriftspresentasjoner og andre arrangementer. " ), ) objects = NablaUserManager() def get_class_number(self): """Henter hvilken klasse på fysmat (1-5) brukeren går i. Returnerer 0 hvis brukeren ikke går på fysmat.""" try: theclass = FysmatClass.objects.filter( user=self).order_by("starting_year")[0] return theclass.get_class_number() except (FysmatClass.DoesNotExist, IndexError): return 0 def get_absolute_url(self): return reverse("member_profile", kwargs={"username": self.username}) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if not self.last_login: self.last_login = datetime.today() return super().save(force_insert, force_update, using, update_fields) @property def nablagroups(self): groups = self.groups.all() return [ NablaGroup.objects.filter(id=group.id).first() for group in groups ] def get_penalties(self): """Returns the EventRegistrations for which the user has penalties this semester""" from nablapps.events.models import ( # Moved down to avoid loop error when FysmatClass was imported to mixins in events EventRegistration, ) # Penalties are valid for six months six_months_ago = timezone.now() - timezone.timedelta( days=182) # about six months penalties = (EventRegistration.objects.filter( user=self, date__gte=six_months_ago).exclude(penalty=0).exclude(penalty=None)) return penalties
class UserPhoto(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) image = ImageCropField(blank=True, upload_to='user_photo') cropping = ImageRatioField('image', '100x100') is_main = models.BooleanField(default=False) is_approved = models.BooleanField(default=False) is_deleted = models.BooleanField(default=False) croppos = models.CharField(default='', max_length=250) def setAsMain(self): UserPhoto.objects.filter(user=self.user).update(is_main=False) self.is_main = True self.save() def get_small_url(self): return get_thumbnailer(self.image).get_thumbnail({ 'size': (50, 50), 'box': self.cropping, 'crop': 'smart', 'upscale': True, }).url @property def get_small_img(self): return mark_safe('<img src="%s" />' % self.get_small_url()) def get_middle_url(self): return get_thumbnailer(self.image).get_thumbnail({ 'size': (200, 200), 'box': self.cropping, 'crop': 'smart', 'upscale': True, }).url @property def get_middle_img(self): return mark_safe('<img src="%s" />' % self.get_middle_url()) def __str__(self): thumbnail_url = get_thumbnailer(self.image).get_thumbnail({ 'size': (50, 50), 'box': self.cropping, 'crop': 'smart', 'upscale': True, }).url return mark_safe('<img src="%s" />' % thumbnail_url) def update_thumbs(self): self.get_small_url() self.get_middle_url() @property def image_big(self): return '%s%s' % (DOMAIN, self.image.url) @property def image_middle(self): url = get_thumbnailer(self.image).get_thumbnail({ 'size': (200, 200), 'box': self.cropping, 'crop': 'smart', 'upscale': True, }).url #return url return '%s%s' % (DOMAIN, url) @property def image_small(self): url = get_thumbnailer(self.image).get_thumbnail({ 'size': (80, 80), 'box': self.cropping, 'crop': 'smart', 'upscale': True, }).url #return url return '%s%s' % (DOMAIN, url)
class Parlamentar(models.Model): FEMININO = 'F' MASCULINO = 'M' SEXO_CHOICE = ((FEMININO, _('Feminino')), (MASCULINO, _('Masculino'))) nivel_instrucao = models.ForeignKey(NivelInstrucao, blank=True, null=True, on_delete=models.PROTECT, verbose_name=_('Nível Instrução')) situacao_militar = models.ForeignKey(SituacaoMilitar, blank=True, null=True, on_delete=models.PROTECT, verbose_name=_('Situação Militar')) nome_completo = models.CharField(max_length=50, verbose_name=_('Nome Completo')) nome_parlamentar = models.CharField(max_length=50, verbose_name=_('Nome Parlamentar')) sexo = models.CharField(max_length=1, verbose_name=_('Sexo'), choices=SEXO_CHOICE) data_nascimento = models.DateField(blank=True, null=True, verbose_name=_('Data Nascimento')) cpf = models.CharField(max_length=14, blank=True, verbose_name=_('C.P.F')) rg = models.CharField(max_length=15, blank=True, verbose_name=_('R.G.')) titulo_eleitor = models.CharField(max_length=15, blank=True, verbose_name=_('Título de Eleitor')) numero_gab_parlamentar = models.CharField(max_length=10, blank=True, verbose_name=_('Nº Gabinete')) telefone = models.CharField(max_length=50, blank=True, verbose_name=_('Telefone')) fax = models.CharField(max_length=50, blank=True, verbose_name=_('Fax')) endereco_residencia = models.CharField( max_length=100, blank=True, verbose_name=_('Endereço Residencial')) municipio_residencia = models.CharField(max_length=50, blank=True, verbose_name=_('Município')) uf_residencia = models.CharField(max_length=2, blank=True, choices=LISTA_DE_UFS, verbose_name=_('UF')) cep_residencia = models.CharField(max_length=9, blank=True, verbose_name=_('CEP')) telefone_residencia = models.CharField( max_length=50, blank=True, verbose_name=_('Telefone Residencial')) fax_residencia = models.CharField(max_length=50, blank=True, verbose_name=_('Fax Residencial')) endereco_web = models.URLField(max_length=100, blank=True, verbose_name=_('HomePage')) profissao = models.CharField(max_length=50, blank=True, verbose_name=_('Profissão')) email = models.EmailField(max_length=100, blank=True, verbose_name=_('E-mail')) locais_atuacao = models.CharField(max_length=100, blank=True, verbose_name=_('Locais de Atuação')) ativo = models.BooleanField(db_index=True, default=False, choices=YES_NO_CHOICES, verbose_name=_('Ativo na Casa?')) biografia = models.TextField(blank=True, verbose_name=_('Biografia')) # XXX Esse atribuito foi colocado aqui para não atrapalhar a migração fotografia = ImageCropField(verbose_name=_('Fotografia'), upload_to=foto_upload_path, validators=[restringe_tipos_de_arquivo_img], null=True, blank=True) cropping = ImageRatioField( 'fotografia', '128x128', verbose_name=_('Avatar'), size_warning=True, help_text=_('A configuração do Avatar ' 'é possível após a atualização da fotografia.')) # campo conceitual de reversão genérica para o model Autor que dá a # o meio possível de localização de tipos de autores. autor = SaplGenericRelation( Autor, related_query_name='parlamentar_set', fields_search=( # na primeira posição dever ser campo simples sem __ ('nome_completo', '__icontains'), ('nome_parlamentar', '__icontains'), ('filiacao__partido__sigla', '__icontains'), )) class Meta: verbose_name = _('Parlamentar') verbose_name_plural = _('Parlamentares') ordering = ['nome_parlamentar'] def __str__(self): return self.nome_parlamentar @property def filiacao_atual(self): ultima_filiacao = self.filiacao_set.order_by('-data').first() if ultima_filiacao and not ultima_filiacao.data_desfiliacao: return ultima_filiacao.partido.sigla else: return _('Sem Partido') @property def avatar_html(self): return '<img class="avatar-parlamentar" src='\ + self.fotografia.url + '>'if self.fotografia else '' def delete(self, using=None, keep_parents=False): if self.fotografia: self.fotografia.delete() return models.Model.delete(self, using=using, keep_parents=keep_parents) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if not self.pk and self.fotografia: fotografia = self.fotografia self.fotografia = None models.Model.save(self, force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields) self.fotografia = fotografia return models.Model.save(self, force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)
class BaseUser(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.EmailField(unique=True) english_names = models.CharField(max_length=50, null=True, blank=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) birth_place = models.ForeignKey(City, null=True, blank=True) github_account = models.URLField(null=True, blank=True) linkedin_account = models.URLField(null=True, blank=True) description = models.TextField(null=True, blank=True) twitter_account = models.URLField(null=True, blank=True) works_at = models.CharField(null=True, blank=True, max_length=110) studies_at = models.CharField(blank=True, null=True, max_length=110) avatar = ImageCropField(blank=True, null=True) full_image = ImageCropField(upload_to='avatars/', blank=True, null=True) cropping = ImageRatioField('full_image', '300x300') created_at = models.DateTimeField(auto_now_add=True, null=True) education_info = models.ManyToManyField(EducationPlace, through='EducationInfo', related_name='info') USERNAME_FIELD = 'email' objects = UserManager() def get_full_name(self): return self.email def get_short_name(self): return self.email def __str__(self): return self.email @property def full_name(self): return "{} {}".format(self.first_name, self.last_name) def get_competitor(self): try: return self.competitor except: return False def get_student(self): try: return self.student except: return False def get_teacher(self): try: return self.teacher except: return False def get_interviewer(self): try: return self.interviewer except: return False def get_english_names(self): return self.english_names
class Image(models.Model): image_field = ImageCropField(upload_to='image/') cropping = ImageRatioField('image_field', '120x100') class Meta: app_label = 'example'
class NablaUser(AbstractUser): telephone = models.CharField(verbose_name="Telefon", max_length=15, blank=True) cell_phone = models.CharField(verbose_name="Mobil", max_length=15, blank=True) birthday = models.DateField(verbose_name="Bursdag", blank=True, null=True) address = models.CharField(verbose_name="Adresse", max_length=40, blank=True) mail_number = models.CharField(verbose_name="Postnr", max_length=4, blank=True) web_page = models.CharField(verbose_name="Hjemmeside", max_length=80, blank=True) wants_email = models.BooleanField(verbose_name="Motta kullmail", default=True) about = models.TextField(verbose_name="Biografi", blank=True) avatar = ImageCropField(verbose_name='Avatar', blank=True, null=True, upload_to='avatars') cropping = ImageRatioField( #assosiated ImageField: 'avatar', #Ratio and Minimum size #(width, height): '140x170', allow_fullsize=True, verbose_name='Beskjæring', size_warning=True, ) ntnu_card_number = models.CharField( verbose_name="NTNU kortnr", max_length=10, blank=True, help_text=("Dette er et 7-10-sifret nummer på baksiden av kortet." "På nye kort er dette sifrene etter EM." "På gamle kort er dette sifrene nede til venstre." "Det brukes blant annet for å komme inn på bedpresser.")) objects = NablaUserManager() def get_hashed_ntnu_card_number(self): """Returnerer sha1-hashen av ntnu kortnummeret som BPC-trenger.""" return sha1(self.ntnu_card_number.encode()).hexdigest() def get_class_number(self): """Henter hvilken klasse på fysmat (1-5) brukeren går i. Returnerer 0 hvis brukeren ikke går på fysmat.""" try: theclass = FysmatClass.objects.filter( user=self).order_by('starting_year')[0] return theclass.get_class_number() except (FysmatClass.DoesNotExist, IndexError): return 0 def get_absolute_url(self): return reverse("member_profile", kwargs={"username": self.username}) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if not self.last_login: self.last_login = datetime.today() return super().save(force_insert, force_update, using, update_fields) @property def nablagroups(self): groups = self.groups.all() return [ NablaGroup.objects.filter(id=group.id).first() for group in groups ] def get_penalties(self): """Returns the EventRegistrations for which the user has penalties this semester""" from nablapps.events.models import EventRegistration #Moved down to avoid loop error when FysmatClass was imported to mixins in events # Find out if we are in first or second term today = date.today() first_semester = date(today.year, 1, 1) # First semester starts 1. jan second_semester = date(today.year, 6, 1) # Second semester starts 6. jun semester_start = second_semester if second_semester <= today else first_semester penalties = EventRegistration.objects.\ filter(user=self, date__gte=semester_start).exclude(penalty=0) return penalties