Esempio n. 1
0
class Fruit(models.Model):
    title = models.CharField(max_length=255, verbose_name=u"标题")
    kinds = TaggableManager(verbose_name=u"水果分类")
    slug = models.ForeignKey(Activity,
                             null=True,
                             blank=True,
                             related_name="fruits_in_activity",
                             verbose_name=u"参加的活动类型")
    image_icon = ImageWithThumbsField(u"首页图片(273x150)",
                                      upload_to="static/images/app",
                                      sizes=((273, 150), ))
    image_content1 = ImageWithThumbsField(upload_to="static/images/app",
                                          blank=True,
                                          verbose_name=u"详细图片(可空)")
    image_content2 = ImageWithThumbsField(upload_to="static/images/app",
                                          blank=True,
                                          verbose_name=u"详细图片(可空)")
    image_content3 = ImageWithThumbsField(upload_to="static/images/app",
                                          blank=True,
                                          verbose_name=u"详细图片(可空)")
    datetime = models.DateTimeField(auto_now=True, verbose_name=u"添加日期")
    content = models.TextField(verbose_name=u"简介(对标题的简述)")
    detail = models.TextField(verbose_name=u"产品详情", blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2, default=10)

    def __unicode__(self):
        return u"{}".format(self.title)

    class Meta:
        verbose_name = u"水果"
        verbose_name_plural = u"水果"
Esempio n. 2
0
class SkyPicture(models.Model):
    """
    Describes a picture captured by a sky imager.
    """

    # Date and time of capture
    date = models.DateField("Date of capture", db_index=True)
    time = models.TimeField("Time of capture", db_index=True)

    # Stores the image with generated thumbnails
    image = ImageWithThumbsField("Image file",
                                 upload_to='sky_images/%Y/%m/%d',
                                 sizes=((125, 125), (1000, 667)))
    # Info at https://code.google.com/p/django-thumbs/

    # Undistorted version of the image to project on the map
    undistorted = models.ImageField("Undistorted image",
                                    upload_to='undistorted/')

    # Image parameters
    exposure_time = models.FloatField(
        "Exposure time")  # stored as the denominator only (1/x)
    aperture_value = models.FloatField("Aperture value")
    ISO_speed = models.IntegerField("ISO speed")

    device = models.ForeignKey('MeasuringDevice',
                               limit_choices_to={'type': 'W'},
                               verbose_name="Measuring device used")

    objects = DateManager()

    def __unicode__(self):
        dt = datetime.datetime.combine(self.date, self.time)
        return dt.strftime('%Y-%m-%d %H:%M') + ' with ' + unicode(self.device)
Esempio n. 3
0
File: models.py Progetto: igor7525/1
class Reviews(models.Model):
	created_at = models.DateTimeField(_('date of creation'), )
	updated_at = models.DateTimeField(_('last modification date'), auto_now=True)
	first_name = models.CharField(_('first name'), max_length=30)
	last_name = models.CharField(_('last name'), max_length=30)
	review = models.TextField(_('review'))
	photo = ImageWithThumbsField(_('photo'), upload_to='review/%Y-%m-%d/', sizes=((128, 128),), default='default-avatar.128x128.jpg')

	class Meta:
		verbose_name = _('review')
		verbose_name_plural = _('reviews')

	def __unicode__(self):

		return _("%(first_name)s %(last_name)s") % {
			'first_name': self.first_name,
			'last_name': self.last_name,
			}

	def admin_thumbnail(self):
		if self.photo:

			return "<img src='%s' height='64px' style='border-radius: 50%%;' />" % (self.photo.thumbnail(128, 128))

		return "<div style='width: 64px; height: 64px; background: aliceblue; text-align: center; display: table-cell; vertical-align: middle; border-radius: 50%;'>No photo</div>"

	admin_thumbnail.short_description = _('photo')
	admin_thumbnail.allow_tags = True
Esempio n. 4
0
class ConfirmOrderInfo(models.Model):
    CONFIRM_ORDER_CHOICES = {
        (0, u'采购员取消'),
        (1, u'客户已下单,待采购员确认'),
        (2, u'采购员,已确认,等待客户付款'),
        (3, u'订单完成'),
        (4, u'客户付款成功,采购员开始采购'),
        (5, u'采购员已发货')

    }
    owner = models.ForeignKey(ProductOwner, verbose_name=u'供应商', related_name='confirmOrderInfo')
    buyer = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=u'买手', related_name ='confirmOrderInfo')
    buyer_phone = models.BigIntegerField(null=True,verbose_name=u'手机号')
    basket = models.ForeignKey('basket.Basket',verbose_name =u'关联购物车信息',related_name='confirmOrderInfo')
    status = models.IntegerField(choices=CONFIRM_ORDER_CHOICES,verbose_name=u'状态')
    server_money = models.FloatField(verbose_name=u'服务费',null=True)
    total_money = models.FloatField(verbose_name=u'总价')
    message = models.CharField(max_length=255,verbose_name=u'买家留言')
    confirm_Id = models.CharField(max_length=255,verbose_name=u'订单号')
    create_date = models.DateTimeField(auto_now_add=True, blank=True,verbose_name=u'创建时间,用户下单时间')
    confirm_time =models.DateTimeField(auto_now_add=True,blank=True,verbose_name=u'用户确认时间')
    confirmPhoto = ImageWithThumbsField(null=True,blank=True,upload_to=settings.IMAGES)



    def save(self, *args, **kwargs):
        self.confirm_id = str(self.id)+str(self.buyer.id)
        super(ConfirmOrderInfo,self).save(*args,**kwargs)
Esempio n. 5
0
class Image(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField(null=True, blank=True)
    copyright = models.CharField("Copyright / Owner",
                                 max_length=200,
                                 blank=True)
    date = models.DateField(blank=True, null=True)
    image = ImageWithThumbsField(upload_to='images/',
                                 sizes=((125, 125), (52, 52), (1300, 1000),
                                        (1000, 1300)))
    region = models.ForeignKey(Region,
                               related_name="image_region",
                               verbose_name="Region")

    def __unicode__(self):
        return u"%s" % (self.name)

    @property
    def image_tag(self):
        return format_html('<img src="{}" />'.format(self.image.url_125x125))

    @property
    def image_size(self):
        suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
        size = int(self.image.size)
        if size == 0: return '0 B'
        i = 0
        while size >= 1024 and i < len(str(size)) - 1:
            size /= 1024.
            i += 1
        f = ('%.2f' % size).rstrip('0').rstrip('.')
        return '%s %s' % (f, suffixes[i])
Esempio n. 6
0
class ProductItem(models.Model):
    """SKU 单品表, 每个单品, 一个唯一的 RFID"""
    # read by hardware
    rfid = models.CharField(u'RFID 标签', max_length=100)
    weight = models.FloatField(u'重量 (g)')
    photo = ImageWithThumbsField(upload_to=settings.PRODUCT_PHOTO,
                                 sizes=((200, 200), (450, 450)))
    shop = models.ForeignKey(Shop, verbose_name=u'门店')  # read by ant ID

    # basic info
    name = models.CharField(u'名称', max_length=100)
    status = models.ForeignKey(ProductStatus, verbose_name=u'状态')
    notes = models.CharField(u'备注', max_length=100, null=True, blank=True)
    scale = models.CharField(u'尺寸 (mm)', max_length=100, null=True, blank=True)

    # detail info
    style = models.ForeignKey(ProductStyle, verbose_name=u'样式')
    material = models.ForeignKey(ProductMaterial, verbose_name=u'材质')

    def __unicode__(self):
        return u'%s(%s)' % (self.name, self.weight)

    class Meta:
        verbose_name = u'物件单品'
        verbose_name_plural = verbose_name
Esempio n. 7
0
class Article(MultilingualModel):
    objects = ArticleManager()
    author = models.ForeignKey(Author)
    created_on = models.DateTimeField(auto_now_add=True)
    modified_on = models.DateTimeField(auto_now=True)
    category = models.ForeignKey(Category)
    graphic = ImageWithThumbsField(upload_to='graphics', sizes=GRAPHIC_SIZES)
    graphic_source = models.URLField(blank=True, null=True)
    is_lead_story = UniqueBooleanField()

    def __unicode__(self):
        return "%s by %s [%s]" % (self.title, self.author, self.category)

    def get_absolute_url(self):
        return reverse('article-detail', args=[self.slug])

    def get_season(self):
        """Returns a string indicating the season in which it was published.
        For example, "Winter 2014"."""
        date = self.created_on.date()

        # Figure out the season from the month
        season_index = (date.month - 1) / 3
        season = SEASON_NAMES[season_index]

        return "%s %d" % (season, date.year)
Esempio n. 8
0
class Brand(Timestamps):
    """docstring for Brand"""
    name = models.CharField(_('name'), max_length=64)
    image = ImageWithThumbsField(_('image'),
                                 upload_to='catalog/brands/%Y-%m-%d/',
                                 null=True,
                                 blank=True,
                                 sizes=((109, 62), ))

    class Meta:
        verbose_name = _('brand')
        verbose_name_plural = _('brands')

    def __unicode__(self):

        return _("%(name)s") % {'name': self.name}

    def admin_thumbnail(self):
        if self.image:

            return "<img src='%s' height='62px' />" % (self.image.thumbnail(
                109, 62))

        return "<div style='width: 109px; height: 62px; background: aliceblue; text-align: center; display: table-cell; vertical-align: middle;'>Нет фото</div>"

    admin_thumbnail.short_description = _('image')
    admin_thumbnail.allow_tags = True
Esempio n. 9
0
class ClientPhoto(SortableMixin):
    image = ImageWithThumbsField(_('image'),
                                 upload_to=get_photos_folder,
                                 sizes=((250, 150), (64, 64)))
    description = models.TextField(_('description'))
    order = models.PositiveIntegerField(default=0,
                                        editable=False,
                                        db_index=True)

    class Meta:
        ordering = [
            "order",
        ]
        verbose_name = _('photo')
        verbose_name_plural = _('photo')

    def __unicode__(self):
        return _("%(image)s") % {'image': self.image.url}

    @property
    def get_short_description(self):
        if len(self.description) > 200:
            return self.description[:201] + '...'
        else:
            return self.description

    def view_photo(self):
        return "<img src='%s' height='64px' />" % (self.image.thumbnail(
            64, 64))

    @property
    def middle_photo(self):
        return self.image.thumbnail(250, 150)
Esempio n. 10
0
class Fruit(models.Model):
    title = models.CharField(max_length=255, verbose_name=u"标题")
    kinds = TaggableManager(verbose_name=u"水果分类")
    slug = models.ForeignKey(Activity,
                             null=True,
                             blank=True,
                             related_name="fruits_in_activity",
                             verbose_name=u"参加的活动类型")
    image_icon = ImageWithThumbsField(u"首页图片(273x150)",
                                      upload_to="static/images/app",
                                      sizes=((273, 150), ))
    image_content1 = ImageWithThumbsField(upload_to="static/images/app",
                                          blank=True,
                                          help_text=u"详细图片(可空)")
    image_content2 = ImageWithThumbsField(upload_to="static/images/app",
                                          blank=True,
                                          verbose_name=u"详细图片(可空)")
    image_content3 = ImageWithThumbsField(upload_to="static/images/app",
                                          blank=True,
                                          verbose_name=u"详细图片(可空)")
    datetime = models.DateTimeField(auto_now=True, verbose_name=u"添加日期")
    content = models.TextField(verbose_name=u"简介(对标题的简述)")
    detail = models.TextField(verbose_name=u"产品详情", blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2, default=10)

    def __unicode__(self):
        return u"{}".format(self.title)

    class Meta:
        ordering = ['title']
        verbose_name = u"水果"
        verbose_name_plural = u"水果"

    @property
    def full_image_content1(self):
        if hasattr(self.image_content1, 'url'):
            return "http://118.31.43.180" + self.image_content1.url
        return ""

    @property
    def full_image_icon(self):
        return "http://118.31.43.180" + self.image_icon.url

    @property
    def tag_name(self):
        return self.kinds.values()[0]["name"]
Esempio n. 11
0
class Activity(models.Model):
    category = models.CharField(max_length=100, verbose_name=u"活动类型")
    image = ImageWithThumbsField(upload_to="static/images/activity", null=True)

    def __unicode__(self):
        return u"{}, id:{}".format(self.category, self.id)

    class Meta:
        verbose_name = u"首页最新活动图片,为了美观,图片大小不要相差太多"
        verbose_name_plural = u"首页最新活动图片,为了美观,图片大小不要相差太多"
Esempio n. 12
0
class GameInstanceSnapshot(TimestamperMixin, models.Model):
    instance = models.ForeignKey(GameInstance, related_name='images')
    image = ImageWithThumbsField(sizes=((125, 125), (200, 200)))
    time = models.FloatField(default=0, blank=False)

    def __unicode__(self):
        return self.instance.game.title + ", " + str(self.created)

    def getFilename(self):
        return self.image.name or None
Esempio n. 13
0
class PortfolioItem(models.Model):
    title = models.CharField(max_length=100)
    subtitle = models.CharField(max_length=500, blank=True)
    category = models.ForeignKey(PortfolioCategory)
    description = models.TextField()
    sourcecode = models.URLField()
    image = ImageWithThumbsField(null=True, sizes=((125,125),(200,200)))
    year = models.IntegerField()
    month = models.IntegerField()

    def __unicode__(self):
        return self.title
Esempio n. 14
0
File: models.py Progetto: igor7525/1
class News(Timestamps):
	title = models.CharField(_('title'), max_length=64)
	text = models.TextField(_('text'))

	miniature = ImageWithThumbsField(_('miniature'), upload_to='news/%Y-%m-%d/', blank=True, null=True, sizes=((298, 176),))

	class Meta:
		verbose_name = _('news')
		verbose_name_plural = _('news')

	def __unicode__(self):

		return _("%(title)s") % {'title': self.title}
Esempio n. 15
0
class PortfolioCategory(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(null=True)
    short_description = models.TextField(null=True)
    image = ImageWithThumbsField(null=True, sizes=((125,125),(200,200)))
    deployment_type = models.CharField(max_length=50, choices=DEPLOYMENT_CHOICES, default='canvasapp')

    def __unicode__(self):
        return self.name

    def num_items(self):
        items = PortfolioItem.objects.filter(category__id=self.id)
        return len(items)
Esempio n. 16
0
class Article(models.Model):
    title = models.CharField(max_length=60,verbose_name='标题')
    channel = models.ForeignKey(Channel,verbose_name='所属栏目')
    keywords = models.CharField(max_length=80,verbose_name='关键字')
    description = models.CharField(max_length=200,verbose_name='栏目描述')
    author = models.CharField(max_length=30,blank=True,verbose_name='作者')
    date = models.DateField(verbose_name = '发布时间')
	#    image = ImageWithThumbsField(blank=True,verbose_name=u'缩略图',upload_to='uploads')
    image1 = ImageWithThumbsField(blank=True,verbose_name=u'网站缩略图',upload_to='uploads')
    click = models.IntegerField(default=0,verbose_name='点击次数')
    content = RichTextField(verbose_name = '文档内容')
    def __unicode__(self):
        return u'%s %s' % (self.title,self.channel)
    class Meta:
        ordering = ['-id']
        verbose_name_plural = '文档管理'
Esempio n. 17
0
class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    language = models.CharField(max_length=100, default='en-GB')
    bio = SanitizedTextField(default='', allowed_tags=settings.SANITIZER_ALLOWED_TAGS, allowed_attributes=settings.SANITIZER_ALLOWED_ATTRIBUTES)
    question_basket = models.ManyToManyField(NewQuestion, blank=True, related_name='baskets', through='BasketQuestion')
    personal_project = models.ForeignKey(Project, null=True, on_delete=models.SET_NULL,related_name='personal_project_of')
    avatar = ImageWithThumbsField(upload_to='avatars', sizes=((20, 20), (40, 40), (150, 150)), blank=True, null=True, max_length=255, verbose_name='Profile image')
    wrap_lines = models.BooleanField(default=False,verbose_name='Wrap long lines in the code editor?')
    mathjax_url = models.CharField(max_length=300,default='',blank=True,verbose_name='Preferred URL to load MathJax from')

    def sorted_tags(self):
        qs = self.user.own_questions
        tags = EditorTag.objects.filter(question__author=self.user).distinct()
        tag_counts = [(tag, len(qs.filter(tags__id=tag.id))) for tag in tags]
        tag_counts.sort(key=itemgetter(1), reverse=True)

        return tag_counts

    @property
    def recent_questions(self):
        return NewQuestion.objects.filter(editoritem__author=self.user).order_by('-editoritem__last_modified')[:10]

    def projects(self):
        return (Project.objects.filter(owner=self.user) | Project.objects.filter(projectaccess__user=self.user)).distinct().order_by(Lower('name'))

    def all_timeline(self):
        projects = self.user.own_projects.all() | Project.objects.filter(projectaccess__in=self.user.project_memberships.all()) | Project.objects.filter(watching_non_members=self.user)
        nonsticky_broadcasts = SiteBroadcast.objects.visible_now().exclude(sticky=True)
        nonsticky_broadcast_timelineitems = TimelineItem.objects.filter(object_content_type=ContentType.objects.get_for_model(SiteBroadcast), object_id__in=nonsticky_broadcasts)

        items = TimelineItem.objects.filter(
            Q(editoritems__in=self.user.watched_items.all()) | 
            Q(editoritems__project__in=projects) |
            Q(projects__in=projects)
        )

        items = (items | nonsticky_broadcast_timelineitems).order_by('-date')

        return items

    def public_timeline(self):
        return self.user.timelineitems.order_by('-date')

    def get_absolute_url(self):
        return reverse('view_profile', args=(self.pk,))
Esempio n. 18
0
class Photo(Timestamps, SortableMixin):
    image = ImageWithThumbsField(_('image'),
                                 upload_to=get_dir_name_cat,
                                 sizes=((298, 176), (64, 64)))
    product = models.ForeignKey("Products",
                                verbose_name=_('photo'),
                                related_name='photos')
    order = models.PositiveIntegerField(default=0,
                                        editable=False,
                                        db_index=True)

    class Meta:
        ordering = [
            "order",
        ]
        verbose_name = _('photo')
        verbose_name_plural = _('photo')

    def __unicode__(self):

        return _("%(image)s") % {'image': self.image.url}
Esempio n. 19
0
File: models.py Progetto: igor7525/1
class OurAdvantages(Timestamps):
	"""docstring for OurAdvantages"""
	title = models.CharField(_('title'), max_length=64)
	description = models.TextField(_('description'))
	show = models.BooleanField(_('is show'), default=True)

	image = ImageWithThumbsField(_('image'), upload_to='advantages/%Y-%m-%d/', sizes=((64, 64),))

	class Meta:
		verbose_name = _('our advantages')
		verbose_name_plural = _('our advantages')

	def admin_thumbnail(self):
		if self.image:

			return "<img src='%s' height='64px' />" % (self.image.thumbnail(64, 64))

		return "<div style='width: 64px; height: 64px; background: aliceblue; text-align: center; display: table-cell; vertical-align: middle;'>No photo</div>"

	admin_thumbnail.short_description = _('image')
	admin_thumbnail.allow_tags = True
Esempio n. 20
0
File: models.py Progetto: igor7525/1
class Banner(Timestamps):
	title = models.CharField(_('title'), max_length=64)
	text = models.TextField(_('text'))
	show = models.BooleanField(_('is show'), default=True)
	url = models.CharField(_('url'), max_length=128, default="/")

	image = ImageWithThumbsField(upload_to='banner/%Y-%m-%d/', sizes=((195, 64),))

	class Meta:
		verbose_name = _('banner')
		verbose_name_plural = _('banners')

	def admin_thumbnail(self):
		if self.image:

			return "<img src='%s' height='64px' />" % (self.image.thumbnail(195, 64))

		return "<div style='width: 195px; height: 64px; background: aliceblue; text-align: center; display: table-cell; vertical-align: middle;'>No photo</div>"

	admin_thumbnail.short_description = _('banner')
	admin_thumbnail.allow_tags = True
Esempio n. 21
0
class Category(models.Model):
    name = models.CharField(max_length=1000)
    parent = models.ForeignKey('self',
                               null=True,
                               blank=True,
                               related_name="children")
    description = models.TextField(null=True, blank=True)
    image = ImageWithThumbsField(null=True,
                                 blank=True,
                                 sizes=((125, 125), (200, 200), (300, 300)))
    enabled = models.BooleanField(null=False, blank=False, default=True)
    popularity = models.IntegerField(default=1)

    def __unicode__(self):
        return self.name

    def get_total_popularity(self):
        return sum(map(lambda app: app.popularity, self.apps.all()))

    def get_avg_popularity(self):
        return sum(map(lambda app: app.popularity,
                       self.apps.all())) / self.apps.count()
Esempio n. 22
0
class ImageModel(models.Model):
    image = ImageWithThumbsField(sizes=((125,125),(200,200)))
    timestamp = models.DateTimeField(default=now, editable=False)
    gallery = models.ForeignKey(ImageGallery, null=True, related_name='images')
Esempio n. 23
0
class Photo(models.Model):
    title = models.CharField(max_length=140)
    image = ImageWithThumbsField(upload_to='photos', sizes=((125, 125),))
Esempio n. 24
0
class StoryLinePart(models.Model):
    headline = models.CharField(max_length=100)
    description = models.TextField(blank=True)
    image_name = models.CharField(max_length=200, null=True, blank=True)
    image_description = models.TextField(null=True, blank=True)
    image_copyright = models.CharField("Copyright / Owner",
                                       max_length=200,
                                       blank=True)
    image_date = models.DateField(blank=True, null=True)
    image = ImageWithThumbsField(
        upload_to='images/',
        sizes=((125, 125), (200, 300), (300, 200), (600, 400), (400, 600)),
        null=True,
        blank=True,
        help_text=
        "To avoid cutting off parts of your image please resize it in advance. Right position: max. 300px width; Bottom max. 600px. If you upload a GIF please make sure the size is not higher than 500kb"
    )
    image_position = models.CharField(max_length=20,
                                      choices=(("right", "right"), ("bottom",
                                                                    "bottom")),
                                      default="right")
    region = models.ForeignKey(
        Region,
        help_text=
        "Plaese click - Save and continue editing - to update the layer lists below"
    )
    product_layer = models.ManyToManyField(Layer, blank=True)
    indicator_layer = models.ManyToManyField(Layer,
                                             blank=True,
                                             related_name="indicator_layer")
    external_layer = models.ManyToManyField(Layer,
                                            blank=True,
                                            related_name="external_layer")
    features = models.ManyToManyField(StoryLineFeature, blank=True)
    remove_layer = models.BooleanField(
        default="False", help_text="Remove added layer on the next step")
    west = models.FloatField("BBOX west coordinate",
                             blank=True,
                             null=True,
                             help_text="e.g. -5,3")
    east = models.FloatField("BBOX east coordinate",
                             blank=True,
                             null=True,
                             help_text="e.g. 10,5")
    north = models.FloatField("BBOX north coordinate",
                              blank=True,
                              null=True,
                              help_text="e.g. 8,2")
    south = models.FloatField("BBOX south coordinate",
                              blank=True,
                              null=True,
                              help_text="e.g. -3,9")

    def __unicode__(self):
        return u"%s" % (self.wetland.name + "_" + self.headline)

    @property
    def image_tag(self):
        if not self.image:
            return ""
        return format_html('<img src="{}" />'.format(self.image.url_125x125))

    @property
    def image_url_125(self):
        if not self.image:
            return ""

        return (self.image.url_125x125)

    def image_url_300(self):
        if not self.image:
            return ""

        # use original image if width is or smaller than 300
        if self.image.width <= 300:
            return self.image.url

        # use original image if size is samller than 200kb and width <= 600
        if self.image.width <= 300:
            return self.image.url

        # detect landscape or portrait format
        if self.image.width > self.image.height:
            return self.image.url_300x200
        else:
            return self.image.url_200x300

    def image_url_600(self):
        if not self.image:
            return ""

        # use original image if width is or smaller than 600
        if self.image.width <= 600:
            return self.image.url

        # detect landscape or portrait format
        if self.image.width > self.image.height:
            return self.image.url_600x400
        else:
            return self.image.url_400x600
Esempio n. 25
0
class Project(models.Model):
    user_owner = models.ForeignKey(User)

    public = models.BooleanField(_("Public"), default=True, blank=True)

    featured = models.BooleanField(_("Featured"), default=False, blank=True)

    featured_date = models.DateTimeField('Time featured',
                                         null=True,
                                         blank=True,
                                         default=datetime.utcnow)

    red_flagged = models.BooleanField(_("Red Flagged"),
                                      default=False,
                                      blank=True)

    deleted = models.BooleanField(_("Deleted"), default=False, blank=True)

    first_posted = models.DateTimeField('First Posted',
                                        blank=True,
                                        default=datetime.utcnow)

    last_edited = models.DateTimeField('Last Edited',
                                       blank=True,
                                       default=datetime.utcnow)

    ###############
    # Externals
    #   - Public facing information
    ###############

    title = models.CharField(_('Title'), max_length=254, blank=True, null=True)

    slug = models.SlugField(_('Slug'), blank=True, null=True)

    wallet = models.CharField(_('wallet'),
                              max_length=254,
                              blank=True,
                              null=True)

    btc_amount = models.IntegerField(
        _('BTC Amount'),
        default=0,
    )

    stripe_amount = models.IntegerField(
        _('Stripe Amount'),
        default=0,
    )

    target = models.IntegerField()

    tags = TaggableManager()

    # Thumbnail. We might have to nuke this.
    thumbnail = ImageWithThumbsField(_('Thumbnail'),
                                     upload_to='uploads',
                                     sizes=((125, 125), (200, 200)),
                                     blank=True,
                                     null=True)

    description = models.TextField(_('Description'), blank=True, null=True)

    description_mkd = models.TextField(_('Description (Markdown)'),
                                       blank=True,
                                       null=True)
Esempio n. 26
0
class Student(User, CustomFieldModel):
    mname = models.CharField(max_length=150,
                             blank=True,
                             null=True,
                             verbose_name="Middle Name")
    grad_date = models.DateField(blank=True,
                                 null=True,
                                 validators=settings.DATE_VALIDATORS)
    pic = ImageWithThumbsField(upload_to="student_pics",
                               blank=True,
                               null=True,
                               sizes=((70, 65), (530, 400)))
    alert = models.CharField(
        max_length=500,
        blank=True,
        help_text="Warn any user who accesses this record with this text")
    sex = models.CharField(max_length=1,
                           choices=(('M', 'Male'), ('F', 'Female')),
                           blank=True,
                           null=True)
    bday = models.DateField(blank=True,
                            null=True,
                            verbose_name="Birth Date",
                            validators=settings.DATE_VALIDATORS)
    year = models.ForeignKey(GradeLevel,
                             blank=True,
                             null=True,
                             on_delete=models.SET_NULL,
                             verbose_name="Grade level")
    class_of_year = models.ForeignKey(ClassYear,
                                      verbose_name="Graduating Class",
                                      blank=True,
                                      null=True)
    date_dismissed = models.DateField(blank=True,
                                      null=True,
                                      validators=settings.DATE_VALIDATORS)
    reason_left = models.ForeignKey(ReasonLeft, blank=True, null=True)
    unique_id = models.IntegerField(
        blank=True,
        null=True,
        unique=True,
        help_text="For integration with outside databases")
    ssn = models.CharField(
        max_length=11, blank=True,
        null=True)  #Once 1.1 is out USSocialSecurityNumberField(blank=True)

    # These fields are cached from emergency contacts
    parent_guardian = models.CharField(max_length=150,
                                       blank=True,
                                       editable=False)
    street = models.CharField(max_length=150, blank=True, editable=False)
    state = models.CharField(max_length=255, blank=True)
    city = models.CharField(max_length=255, blank=True)
    zip = models.CharField(max_length=10, blank=True, editable=False)
    parent_email = models.EmailField(blank=True, editable=False)

    family_preferred_language = models.ForeignKey(LanguageChoice,
                                                  blank=True,
                                                  null=True,
                                                  default=get_default_language)
    family_access_users = models.ManyToManyField(
        family_ref,
        blank=True,
        related_name="+",
    )
    alt_email = models.EmailField(
        blank=True,
        help_text="Alternative student email that is not their school email.")
    notes = models.TextField(blank=True)
    emergency_contacts = models.ManyToManyField(EmergencyContact,
                                                verbose_name="Student Contact",
                                                blank=True)
    siblings = models.ManyToManyField('Student', blank=True)
    cohorts = models.ManyToManyField(Cohort,
                                     through='StudentCohort',
                                     blank=True)
    cache_cohort = models.ForeignKey(Cohort,
                                     editable=False,
                                     blank=True,
                                     null=True,
                                     on_delete=models.SET_NULL,
                                     help_text="Cached primary cohort.",
                                     related_name="cache_cohorts")
    individual_education_program = models.BooleanField(default=False)
    gpa = CachedDecimalField(editable=False,
                             max_digits=5,
                             decimal_places=2,
                             blank=True,
                             null=True)

    class Meta:
        permissions = (
            ("view_student", "View student"),
            ("view_ssn_student", "View student ssn"),
            ("view_mentor_student", "View mentoring information student"),
            ("reports", "View reports"),
        )
        ordering = ("last_name", "first_name")

    def __unicode__(self):
        return u"{0}, {1}".format(self.last_name, self.first_name)

    def get_absolute_url():
        pass

    # TC requested this for transcript template
    def get_long_grad_date(self):
        return self.grad_date.strftime('%B %d, %Y')

    def get_gpa(self, rounding=2, numeric_scale=False, boost=True):
        """ Get cached gpa but with rounding and scale options """
        gpa = self.gpa

        if numeric_scale == True:
            # Get the scale for the last year the student was active in
            grade_scale = GradeScale.objects.filter(
                schoolyear__markingperiod__coursesection__courseenrollment__user
                =self).last()
            if grade_scale:
                gpa = grade_scale.to_numeric(gpa)
                enrollments = self.courseenrollment_set.filter(
                    course_section__course__course_type__weight__gt=0)
                if boost:
                    boost_sum = enrollments.aggregate(boost_sum=Sum(
                        'course_section__course__course_type__boost')
                                                      )['boost_sum']
                    boost_factor = boost_sum / enrollments.count()
                    gpa += boost_factor
        if rounding:
            gpa = round_as_decimal(gpa, rounding)
        return gpa

    def calculate_gpa(self,
                      date_report=None,
                      rounding=2,
                      prescale=False,
                      boost=True):
        """ Use StudentYearGrade calculation
        No further weighting needed.
        """
        total = Decimal(0)
        years_with_grade = 0
        grade_years = self.studentyeargrade_set.filter(
            year__markingperiod__show_reports=True)
        if date_report:
            grade_years = grade_years.filter(year__start_date__lt=date_report)
        for grade_year in grade_years.distinct():

            # grade = grade_year.calculate_grade(date_report=date_report, prescale=prescale)

            grade = grade_year.get_grade(date_report=date_report,
                                         numeric_scale=True,
                                         rounding=rounding,
                                         prescale=prescale,
                                         boost=boost)
            if grade:
                # Is this an incomplete complete year?
                if date_report and date_report < grade_year.year.end_date:
                    # This year hasn't finished. What fraction is complete?
                    all_mps = grade_year.year.markingperiod_set.count()
                    complete_mps = grade_year.year.markingperiod_set.filter(
                        end_date__lte=date_report).count()
                    fraction = Decimal(complete_mps) / all_mps
                    total += grade * grade_year.credits * fraction
                    years_with_grade += grade_year.credits * fraction
                else:
                    total += grade * grade_year.credits
                    years_with_grade += grade_year.credits

        if years_with_grade:
            gpa = total / years_with_grade
            return round_as_decimal(gpa, decimal_places=rounding)

    @property
    def primary_cohort(self):
        return self.cache_cohort

    @property
    def phone(self):
        try:
            parent = self.emergency_contacts.order_by('-primary_contact')[0]
            return parent.emergencycontactnumber_set.all()[0].number
        except IndexError:
            return None

    @property
    def he_she(self):
        """ returns "he" or "she" """
        return self.gender_to_word("he", "she")

    @property
    def homeroom(self):
        """ Returns homeroom for student """
        from schedule.models import CourseSection
        try:
            courses = self.coursesection_set.filter(course__homeroom=True)
            homeroom = self.coursesection_set.get(course__homeroom=True)
        except:
            return ""

    @property
    def son_daughter(self):
        """ returns "son" or "daughter" """
        return self.gender_to_word("son", "daughter")

    @property
    def get_email(self):
        """ Returns email address using various configurable methods """
        email_method = Configuration.get_or_default(
            "How to obtain student email",
            default="append",
            help_text="append, user, or student.").value
        if email_method == "append":
            email_end = Configuration.get_or_default(
                "email", default="@change.me").value
            return '%s%s' % (self.student.username, email_end)
        elif email_method == "user":
            if User.objects.filter(username=self.student.username):
                return User.objects.filter(
                    username=self.student.username)[0].email
            return None
        return self.alt_email

    def get_phone_number(self):
        if self.studentnumber_set.filter(type="C"):
            return self.studentnumber_set.filter(type="C")[0]
        elif self.studentnumber_set.all():
            return self.studentnumber_set.all()[0]

    def get_primary_emergency_contact(self):
        if self.emergency_contacts.filter(primary_contact=True):
            return self.emergency_contacts.filter(primary_contact=True)[0]

    def get_disciplines(self, mps, action_name=None, count=True):
        """ Shortcut to look up discipline records
        mp: Marking Period
        action_name: Discipline action name
        count: Boolean - Just the count of them """
        if hasattr(mps, 'db'):  # More than one?
            if len(mps):
                start_date = mps.order_by('start_date')[0].start_date
                end_date = mps.order_by('-end_date')[0].end_date
                disc = self.studentdiscipline_set.filter(
                    date__range=(start_date, end_date))
            else:
                disc = self.studentdiscipline_set.none()
        else:
            disc = self.studentdiscipline_set.filter(
                date__range=(mps.start_date, mps.end_date))
        if action_name:
            disc = disc.filter(action__name=action_name)
        if count:
            return disc.count()
        else:
            return disc

    def gender_to_word(self, male_word, female_word):
        """ returns a string based on the sex of student """
        if self.sex == "M":
            return male_word
        elif self.sex == "F":
            return female_word
        else:
            return male_word + "/" + female_word

    def cache_cohorts(self):
        cohorts = StudentCohort.objects.filter(student=self)
        if cohorts.filter(primary=True).count():
            self.cache_cohort = cohorts.filter(primary=True)[0].cohort
        elif cohorts.count():
            self.cache_cohort = cohorts[0].cohort
        else:
            self.cache_cohort = None

    def get_year(self, active_year):
        """ get the year (fresh, etc) from the class of XX year.
        """
        if self.class_of_year:
            try:
                this_year = active_year.end_date.year
                school_last_year = GradeLevel.objects.order_by('-id')[0].id
                class_of_year = self.class_of_year.year

                target_year = school_last_year - (class_of_year - this_year)
                return GradeLevel.objects.get(id=target_year)
            except:
                return None

    def get_scaled_multiple_mp_average_by_indices(self, indices, rounding=2):
        """ Get a scaled mulitple marking period average for this student
        Requires that the property mps be set previously.
        This function exists mainly for appy based report cards where speed,
        and simplicity (in the template) are important.
        """
        from grades.models import Grade
        mps = [self.mps[i] for i in indices]
        return Grade.get_scaled_multiple_mp_average(self, mps, rounding)

    def determine_year(self):
        """ Set the year (fresh, etc) from the class of XX year.
        """
        if self.class_of_year:
            try:
                active_year = SchoolYear.objects.filter(active_year=True)[0]
                self.year = self.get_year(active_year)
            except:
                return None

    def save(self, creating_worker=False, *args, **kwargs):
        self.cache_cohorts()
        if self.is_active == False and (Configuration.get_or_default("Clear Placement for Inactive Students","False").value == "True" \
        or Configuration.get_or_default("Clear Placement for Inactive Students","False").value == "true" \
        or Configuration.get_or_default("Clear Placement for Inactive Students","False").value == "T"):
            try:
                self.studentworker.placement = None
                self.studentworker.save()
            except:
                pass
        # Check year
        self.determine_year()
        super(Student, self).save(*args, **kwargs)

        # Create student worker if the app is installed.
        # https://code.djangoproject.com/ticket/7623
        if 'work_study' in settings.INSTALLED_APPS:
            if not creating_worker and not hasattr(self, 'studentworker'):
                from work_study.models import StudentWorker
                worker = StudentWorker(user_ptr_id=self.user_ptr_id)
                worker.__dict__.update(self.__dict__)
                worker.save(creating_worker=True)

        group, gcreated = Group.objects.get_or_create(name="students")
        self.user_ptr.groups.add(group)

    def clean(self, *args, **kwargs):
        """ Check if a Faculty exists, can't have someone be a Student and Faculty """
        if Faculty.objects.filter(id=self.id).count():
            raise ValidationError(
                'Cannot have someone be a student AND faculty!')
        super(Student, self).clean(*args, **kwargs)

    def graduate_and_create_alumni(self):
        self.inactive = True
        self.reason_left = ReasonLeft.objects.get_or_create(
            reason="Graduated")[0]
        if not self.grad_date:
            self.grad_date = date.today()
        if 'alumni' in settings.INSTALLED_APPS:
            from alumni.models import Alumni
            Alumni.objects.get_or_create(student=self)
        self.save()

    def promote_to_worker(self):
        """ Promote student object to a student worker keeping all fields, does nothing on duplicate. """
        try:
            cursor = connection.cursor()
            cursor.execute(
                "insert into work_study_studentworker (student_ptr_id) values ("
                + str(self.id) + ");")
        except:
            return
Esempio n. 27
0
class User(AbstractUser):
    avatar = ImageWithThumbsField(upload_to='user/%Y-%m-%d/', blank=True, null=True, sizes=((136, 136),), default='default-avatar.136x136.jpg')
    position = models.CharField(_('position'), max_length=64, blank=True, null=True)
    phone = models.CharField(_('Phone'), max_length=64)
    phone_2 = models.CharField(_('Additional phone'), max_length=64, blank=True, null=True)
Esempio n. 28
0
class MyUser(AbstractBaseUser):
    MAIL = 1
    FEMAIL = 2
    GENDER_CHOICES = (
        (MAIL, u'男'),
        (FEMAIL, u'女'),
    )

    S_PENDING_REVIEW = 1
    S_NORMAL = 2
    S_BANNED = 9

    STATUS_CHOICES = (
        (S_PENDING_REVIEW, u'待审核'),
        (S_NORMAL, u'正常'),
        (S_BANNED, u'已禁用'),
    )

    FANS = 1
    ATHLETE = 2
    BOSS = 3

    ROLE_CHOICES = (
        (FANS, u'球迷'),
        (ATHLETE, u'运动员'),
        (BOSS, u'俱乐部老板'),
    )

    # basic info
    nick_name = models.CharField(u'昵称', max_length=256, blank=True, null=True)
    offical_name = models.CharField(u'真实姓名',
                                    max_length=256,
                                    blank=True,
                                    null=True)
    hide_offical_name = models.BooleanField(u'真实姓名保密', default=False)
    gender = models.IntegerField(u'性别',
                                 choices=GENDER_CHOICES,
                                 null=True,
                                 blank=True)
    avatar = ImageWithThumbsField(upload_to=settings.USER_AVATAR,
                                  default=settings.USER_AVATAR_DEFAULT,
                                  sizes=((200, 200), (450, 450)),
                                  verbose_name=u'头像')

    role = models.IntegerField(u'角色', choices=ROLE_CHOICES, default=FANS)
    status = models.IntegerField(u'状态',
                                 choices=STATUS_CHOICES,
                                 default=S_NORMAL)

    # 1. must have a single unique field that can be used for identification purposes
    # 2. provide a way to address the user in a “short” and “long” form
    username = models.CharField(u'用户名',
                                max_length=32,
                                unique=True,
                                db_index=True)
    is_staff = models.BooleanField('系统管理员', default=False)

    objects = MyUserManager()

    USERNAME_FIELD = 'username'
    # A list of the field names that will be prompted for when creating a user via the createsuperuser management command.
    REQUIRED_FIELDS = []

    @property
    def is_active(self):
        return self.status != self.S_BANNED

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username

    def __unicode__(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 Meta:
        verbose_name = u'用户'
        verbose_name_plural = verbose_name
Esempio n. 29
0
class Beer(models.Model):
    """A Beer Object containing everything we
    need to know about our beer"""
    class Meta:
        ordering = ['name']

    def get_image_path(self, filename):
        extension = filename.split('.')[-1]
        return 'images/uploads/%s.%s' % (slugify(self.name), extension)

    name = models.CharField(max_length=255, unique=True)
    slug = models.SlugField(null=True, blank=True)
    author = models.ForeignKey(User, null=True, blank=True)

    brewery = models.ForeignKey(Brewery)
    created = models.DateTimeField(auto_now_add=True)
    beer_type = models.ForeignKey(BeerType)
    alcohol_by_volume = models.FloatField()
    image = ImageWithThumbsField(upload_to=get_image_path,
                                 sizes=((200, 200), (600, 800)),
                                 null=True,
                                 blank=True)

    comments = models.TextField(null=True, blank=True)

    # Beer Rating and Score Inputs
    appearance_score = models.ForeignKey(Rating,
                                         related_name='beer_appearance')
    appearance = models.TextField()

    smell_score = models.ForeignKey(Rating, related_name='beer_smell')
    smell = models.TextField()

    taste_score = models.ForeignKey(Rating, related_name='beer_taste')
    taste = models.TextField()

    mouthfeel_score = models.ForeignKey(Rating, related_name='beer_mouthfeel')
    mouthfeel = models.TextField()

    overall_score = models.ForeignKey(Rating, related_name='beer_overall')
    overall = models.TextField()

    @property
    def rating(self):
        """Sum up all our scores and get our average rating"""
        return sum([
            self.appearance_score.value, self.smell_score.value,
            self.taste_score.value, self.mouthfeel_score.value,
            self.overall_score.value
        ]) / 5

    def __unicode__(self):
        return self.name

    def save(self, *args, **kwargs):

        self.slug = slugify(self.name)

        super(Beer, self).save(*args, **kwargs)

        if self.image:
            extension = self.image.path.split('.')[-1]
            path = '/'.join(self.image.path.split('/')[:-1])

            remove('%s/%s.%s' % (path, slugify(self.name), extension))

            symlink('%s/%s.600x800.%s' % (path, slugify(self.name), extension),
                    '%s/%s.%s' % (path, slugify(self.name), extension))