Ejemplo n.º 1
0
class Migration(migrations.Migration):

    dependencies = [
        ('main', '0001_initial'),
        ('escuela', '0002_auto_20180502_0030'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='diahora',
            name='grupo',
        ),
        migrations.AddField(
            model_name='grupo',
            name='domingo',
            field=models.BooleanField(default=False),
        ),
        migrations.AddField(
            model_name='grupo',
            name='hora_fin',
            field=models.TimeField(default='8:00'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='grupo',
            name='hora_inicio',
            field=models.TimeField(default='8:00'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='grupo',
            name='jueves',
            field=models.BooleanField(default=False),
        ),
        migrations.AddField(
            model_name='grupo',
            name='lunes',
            field=models.BooleanField(default=False),
        ),
        migrations.AddField(
            model_name='grupo',
            name='martes',
            field=models.BooleanField(default=False),
        ),
        migrations.AddField(
            model_name='grupo',
            name='miercoles',
            field=models.BooleanField(default=False),
        ),
        migrations.AddField(
            model_name='grupo',
            name='sabado',
            field=models.BooleanField(default=False),
        ),
        migrations.AddField(
            model_name='grupo',
            name='viernes',
            field=models.BooleanField(default=False),
        ),
        migrations.AlterUniqueTogether(
            name='grupo',
            unique_together={('id_clase', 'id_profesor', 'hora_inicio',
                              'hora_fin', 'lunes', 'martes', 'miercoles',
                              'jueves', 'viernes', 'sabado', 'domingo')},
        ),
        migrations.DeleteModel(name='DiaHora', ),
    ]
Ejemplo n.º 2
0
class Banner(models.Model):
    title = models.CharField(verbose_name='标题', max_length=50)
    cover = models.ImageField(verbose_name='轮播图', upload_to='static/images/banner')
    link_url = models.URLField(max_length=150, verbose_name='图片链接')
    idx = models.IntegerField(verbose_name='索引')
    is_active = models.BooleanField(verbose_name='是否激活', default=False)
class Migration(migrations.Migration):

    replaces = [('corpus', '0001_initial'),
                ('corpus', '0002_auto_20140918_1733'),
                ('corpus', '0003_auto_20140922_1547'),
                ('corpus', '0004_auto_20140923_1501'),
                ('corpus', '0005_auto_20140923_1502'),
                ('corpus', '0006_auto_20140929_1655'),
                ('corpus', '0007_rename_candidate_evidence_model'),
                ('corpus', '0008_add_evidence_label_model'),
                ('corpus', '0009_data_migration_creating_evidencelabels'),
                ('corpus', '0010_auto_20141009_2027'),
                ('corpus', '0011_auto_20141010_1851'),
                ('corpus', '0012_auto_20141014_1636'),
                ('corpus', '0013_auto_20141014_2136'),
                ('corpus', '0014_remove_segmenttotag_run_number')]

    dependencies = []

    operations = [
        migrations.CreateModel(
            name='Entity',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  primary_key=True,
                                  auto_created=True)),
                ('key', models.CharField(max_length=256)),
            ],
            options={
                'ordering': ['kind', 'key'],
                'abstract': False,
            },
            bases=(models.Model, ),
        ),
        migrations.CreateModel(
            name='EntityKind',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  primary_key=True,
                                  auto_created=True)),
                ('name', models.CharField(unique=True, max_length=256)),
            ],
            options={
                'ordering': ['name'],
                'abstract': False,
            },
            bases=(models.Model, ),
        ),
        migrations.CreateModel(
            name='EntityOccurrence',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  primary_key=True,
                                  auto_created=True)),
                ('offset', models.IntegerField()),
                ('offset_end', models.IntegerField()),
                ('alias', models.CharField(max_length=256)),
            ],
            options={
                'ordering': ['document', 'offset', 'offset_end'],
                'abstract': False,
            },
            bases=(models.Model, ),
        ),
        migrations.CreateModel(
            name='EvidenceCandidate',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  primary_key=True,
                                  auto_created=True)),
                ('left_entity_occurrence',
                 models.ForeignKey(related_name='left_evidence_relations',
                                   to='corpus.EntityOccurrence')),
            ],
            options={
                'ordering': [
                    'segment_id', 'relation_id', 'left_entity_occurrence',
                    'right_entity_occurrence'
                ],
                'abstract':
                False,
            },
            bases=(models.Model, ),
        ),
        migrations.CreateModel(
            name='EvidenceLabel',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  primary_key=True,
                                  auto_created=True)),
                ('label',
                 models.CharField(
                     default='SK',
                     choices=[('NO', 'No relation present'),
                              ('YE', 'Yes, relation is present'),
                              ('DK', "Don't know if the relation is present"),
                              ('SK', 'Skipped labeling of this evidence'),
                              ('NS', 'Evidence is nonsense')],
                     null=True,
                     max_length=2)),
                ('modification_date', models.DateTimeField(auto_now=True)),
                ('judge', models.CharField(max_length=256)),
                ('labeled_by_machine', models.BooleanField(default=True)),
                ('evidence_candidate',
                 models.ForeignKey(related_name='labels',
                                   to='corpus.EvidenceCandidate')),
            ],
            options={
                'abstract': False,
            },
            bases=(models.Model, ),
        ),
        migrations.CreateModel(
            name='IEDocument',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  primary_key=True,
                                  auto_created=True)),
                ('human_identifier',
                 models.CharField(unique=True, max_length=256)),
                ('title', models.CharField(max_length=256)),
                ('url', models.URLField()),
                ('text', models.TextField()),
                ('creation_date', models.DateTimeField(auto_now_add=True)),
                ('tokens', corpus.fields.ListField()),
                ('offsets_to_text', corpus.fields.ListField()),
                ('postags', corpus.fields.ListField()),
                ('sentences', corpus.fields.ListField()),
                ('tokenization_done_at',
                 models.DateTimeField(null=True, blank=True)),
                ('sentencer_done_at',
                 models.DateTimeField(null=True, blank=True)),
                ('tagging_done_at', models.DateTimeField(null=True,
                                                         blank=True)),
                ('ner_done_at', models.DateTimeField(null=True, blank=True)),
                ('segmentation_done_at',
                 models.DateTimeField(null=True, blank=True)),
                ('metadata', jsonfield.fields.JSONField(blank=True)),
            ],
            options={
                'ordering': ['id'],
                'abstract': False,
            },
            bases=(models.Model, ),
        ),
        migrations.CreateModel(
            name='Relation',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  primary_key=True,
                                  auto_created=True)),
                ('name', models.CharField(max_length=256)),
                ('left_entity_kind',
                 models.ForeignKey(related_name='left_relations',
                                   to='corpus.EntityKind')),
                ('right_entity_kind',
                 models.ForeignKey(related_name='right_relations',
                                   to='corpus.EntityKind')),
            ],
            options={
                'ordering': ['name', 'left_entity_kind', 'right_entity_kind'],
                'abstract': False,
            },
            bases=(models.Model, ),
        ),
        migrations.CreateModel(
            name='SegmentToTag',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  primary_key=True,
                                  auto_created=True)),
                ('done', models.BooleanField(default=False)),
                ('modification_date', models.DateTimeField(auto_now=True)),
                ('relation', models.ForeignKey(to='corpus.Relation')),
            ],
            options={
                'abstract': False,
            },
            bases=(models.Model, ),
        ),
        migrations.CreateModel(
            name='TextSegment',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  primary_key=True,
                                  auto_created=True)),
                ('offset', models.IntegerField(db_index=True)),
                ('offset_end', models.IntegerField(db_index=True)),
                ('document',
                 models.ForeignKey(related_name='segments',
                                   to='corpus.IEDocument')),
            ],
            options={
                'ordering': ['document', 'offset', 'offset_end'],
                'abstract': False,
            },
            bases=(models.Model, ),
        ),
        migrations.AlterUniqueTogether(
            name='textsegment',
            unique_together=set([('document', 'offset', 'offset_end')]),
        ),
        migrations.AddField(
            model_name='segmenttotag',
            name='segment',
            field=models.ForeignKey(to='corpus.TextSegment'),
            preserve_default=True,
        ),
        migrations.AlterUniqueTogether(
            name='segmenttotag',
            unique_together=set([('segment', 'relation')]),
        ),
        migrations.AlterUniqueTogether(
            name='relation',
            unique_together=set([('name', 'left_entity_kind',
                                  'right_entity_kind')]),
        ),
        migrations.AlterUniqueTogether(
            name='evidencelabel',
            unique_together=set([('evidence_candidate', 'label', 'judge')]),
        ),
        migrations.AddField(
            model_name='evidencecandidate',
            name='relation',
            field=models.ForeignKey(related_name='evidence_relations',
                                    to='corpus.Relation'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='evidencecandidate',
            name='right_entity_occurrence',
            field=models.ForeignKey(related_name='right_evidence_relations',
                                    to='corpus.EntityOccurrence'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='evidencecandidate',
            name='segment',
            field=models.ForeignKey(related_name='evidence_relations',
                                    to='corpus.TextSegment'),
            preserve_default=True,
        ),
        migrations.AlterUniqueTogether(
            name='evidencecandidate',
            unique_together=set([
                ('left_entity_occurrence', 'right_entity_occurrence',
                 'relation', 'segment')
            ]),
        ),
        migrations.AddField(
            model_name='entityoccurrence',
            name='document',
            field=models.ForeignKey(related_name='entity_occurrences',
                                    to='corpus.IEDocument'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='entityoccurrence',
            name='entity',
            field=models.ForeignKey(to='corpus.Entity'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='entityoccurrence',
            name='segments',
            field=models.ManyToManyField(related_name='entity_occurrences',
                                         to='corpus.TextSegment'),
            preserve_default=True,
        ),
        migrations.AlterUniqueTogether(
            name='entityoccurrence',
            unique_together=set([('entity', 'document', 'offset', 'offset_end')
                                 ]),
        ),
        migrations.AddField(
            model_name='entity',
            name='kind',
            field=models.ForeignKey(to='corpus.EntityKind'),
            preserve_default=True,
        ),
        migrations.AlterUniqueTogether(
            name='entity',
            unique_together=set([('key', 'kind')]),
        ),
    ]
Ejemplo n.º 4
0
class AbstractConditionalOffer(models.Model):
    """
    A conditional offer (eg buy 1, get 10% off)
    """
    name = models.CharField(
        _("Name"), max_length=128, unique=True,
        help_text=_("This is displayed within the customer's basket"))
    slug = fields.AutoSlugField(
        _("Slug"), max_length=128, unique=True, populate_from='name')
    description = models.TextField(_("Description"), blank=True,
                                   help_text=_("This is displayed on the offer"
                                               " browsing page"))

    # Offers come in a few different types:
    # (a) Offers that are available to all customers on the site.  Eg a
    #     3-for-2 offer.
    # (b) Offers that are linked to a voucher, and only become available once
    #     that voucher has been applied to the basket
    # (c) Offers that are linked to a user.  Eg, all students get 10% off.  The
    #     code to apply this offer needs to be coded
    # (d) Session offers - these are temporarily available to a user after some
    #     trigger event.  Eg, users coming from some affiliate site get 10%
    #     off.
    SITE, VOUCHER, USER, SESSION = ("Site", "Voucher", "User", "Session")
    TYPE_CHOICES = (
        (SITE, _("Site offer - available to all users")),
        (VOUCHER, _("Voucher offer - only available after entering "
                    "the appropriate voucher code")),
        (USER, _("User offer - available to certain types of user")),
        (SESSION, _("Session offer - temporary offer, available for "
                    "a user for the duration of their session")),
    )
    offer_type = models.CharField(
        _("Type"), choices=TYPE_CHOICES, default=SITE, max_length=128)

    exclusive = models.BooleanField(
        _("Exclusive offer"),
        help_text=_("Exclusive offers cannot be combined on the same items"),
        default=True
    )

    # We track a status variable so it's easier to load offers that are
    # 'available' in some sense.
    OPEN, SUSPENDED, CONSUMED = "Open", "Suspended", "Consumed"
    status = models.CharField(_("Status"), max_length=64, default=OPEN)

    condition = models.ForeignKey(
        'offer.Condition',
        on_delete=models.CASCADE,
        related_name='offers',
        verbose_name=_("Condition"))
    benefit = models.ForeignKey(
        'offer.Benefit',
        on_delete=models.CASCADE,
        related_name='offers',
        verbose_name=_("Benefit"))

    # Some complicated situations require offers to be applied in a set order.
    priority = models.IntegerField(
        _("Priority"), default=0,
        help_text=_("The highest priority offers are applied first"))

    # AVAILABILITY

    # Range of availability.  Note that if this is a voucher offer, then these
    # dates are ignored and only the dates from the voucher are used to
    # determine availability.
    start_datetime = models.DateTimeField(
        _("Start date"), blank=True, null=True,
        help_text=_("Offers are active from the start date. "
                    "Leave this empty if the offer has no start date."))
    end_datetime = models.DateTimeField(
        _("End date"), blank=True, null=True,
        help_text=_("Offers are active until the end date. "
                    "Leave this empty if the offer has no expiry date."))

    # Use this field to limit the number of times this offer can be applied in
    # total.  Note that a single order can apply an offer multiple times so
    # this is not necessarily the same as the number of orders that can use it.
    # Also see max_basket_applications.
    max_global_applications = models.PositiveIntegerField(
        _("Max global applications"),
        help_text=_("The number of times this offer can be used before it "
                    "is unavailable"), blank=True, null=True)

    # Use this field to limit the number of times this offer can be used by a
    # single user.  This only works for signed-in users - it doesn't really
    # make sense for sites that allow anonymous checkout.
    max_user_applications = models.PositiveIntegerField(
        _("Max user applications"),
        help_text=_("The number of times a single user can use this offer"),
        blank=True, null=True)

    # Use this field to limit the number of times this offer can be applied to
    # a basket (and hence a single order). Often, an offer should only be
    # usable once per basket/order, so this field will commonly be set to 1.
    max_basket_applications = models.PositiveIntegerField(
        _("Max basket applications"),
        blank=True, null=True,
        help_text=_("The number of times this offer can be applied to a "
                    "basket (and order)"))

    # Use this field to limit the amount of discount an offer can lead to.
    # This can be helpful with budgeting.
    max_discount = models.DecimalField(
        _("Max discount"), decimal_places=2, max_digits=12, null=True,
        blank=True,
        help_text=_("When an offer has given more discount to orders "
                    "than this threshold, then the offer becomes "
                    "unavailable"))

    # TRACKING
    # These fields are used to enforce the limits set by the
    # max_* fields above.

    total_discount = models.DecimalField(
        _("Total Discount"), decimal_places=2, max_digits=12,
        default=D('0.00'))
    num_applications = models.PositiveIntegerField(
        _("Number of applications"), default=0)
    num_orders = models.PositiveIntegerField(
        _("Number of Orders"), default=0)

    redirect_url = fields.ExtendedURLField(
        _("URL redirect (optional)"), blank=True)
    date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)

    objects = models.Manager()
    active = ActiveOfferManager()

    # We need to track the voucher that this offer came from (if it is a
    # voucher offer)
    _voucher = None

    class Meta:
        abstract = True
        app_label = 'offer'
        ordering = ['-priority', 'pk']
        verbose_name = _("Conditional offer")
        verbose_name_plural = _("Conditional offers")

    def save(self, *args, **kwargs):
        # Check to see if consumption thresholds have been broken
        if not self.is_suspended:
            if self.get_max_applications() == 0:
                self.status = self.CONSUMED
            else:
                self.status = self.OPEN

        return super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('offer:detail', kwargs={'slug': self.slug})

    def __str__(self):
        return self.name

    def clean(self):
        if (self.start_datetime and self.end_datetime and
                self.start_datetime > self.end_datetime):
            raise exceptions.ValidationError(
                _('End date should be later than start date'))

    @property
    def is_open(self):
        return self.status == self.OPEN

    @property
    def is_suspended(self):
        return self.status == self.SUSPENDED

    def suspend(self):
        self.status = self.SUSPENDED
        self.save()
    suspend.alters_data = True

    def unsuspend(self):
        self.status = self.OPEN
        self.save()
    unsuspend.alters_data = True

    def is_available(self, user=None, test_date=None):
        """
        Test whether this offer is available to be used
        """
        if self.is_suspended:
            return False
        if test_date is None:
            test_date = now()
        predicates = []
        if self.start_datetime:
            predicates.append(self.start_datetime > test_date)
        if self.end_datetime:
            predicates.append(test_date > self.end_datetime)
        if any(predicates):
            return False
        return self.get_max_applications(user) > 0

    def is_condition_satisfied(self, basket):
        return self.condition.proxy().is_satisfied(self, basket)

    def is_condition_partially_satisfied(self, basket):
        return self.condition.proxy().is_partially_satisfied(self, basket)

    def get_upsell_message(self, basket):
        return self.condition.proxy().get_upsell_message(self, basket)

    def apply_benefit(self, basket):
        """
        Applies the benefit to the given basket and returns the discount.
        """
        if not self.is_condition_satisfied(basket):
            return ZERO_DISCOUNT
        return self.benefit.proxy().apply(
            basket, self.condition.proxy(), self)

    def apply_deferred_benefit(self, basket, order, application):
        """
        Applies any deferred benefits.  These are things like adding loyalty
        points to someone's account.
        """
        return self.benefit.proxy().apply_deferred(basket, order, application)

    def set_voucher(self, voucher):
        self._voucher = voucher

    def get_voucher(self):
        return self._voucher

    def get_max_applications(self, user=None):
        """
        Return the number of times this offer can be applied to a basket for a
        given user.
        """
        if self.max_discount and self.total_discount >= self.max_discount:
            return 0

        # Hard-code a maximum value as we need some sensible upper limit for
        # when there are not other caps.
        limits = [10000]
        if self.max_user_applications and user:
            limits.append(max(0, self.max_user_applications -
                          self.get_num_user_applications(user)))
        if self.max_basket_applications:
            limits.append(self.max_basket_applications)
        if self.max_global_applications:
            limits.append(
                max(0, self.max_global_applications - self.num_applications))
        return min(limits)

    def get_num_user_applications(self, user):
        OrderDiscount = get_model('order', 'OrderDiscount')
        aggregates = OrderDiscount.objects.filter(offer_id=self.id,
                                                  order__user=user)\
            .aggregate(total=models.Sum('frequency'))
        return aggregates['total'] if aggregates['total'] is not None else 0

    def shipping_discount(self, charge):
        return self.benefit.proxy().shipping_discount(charge)

    def record_usage(self, discount):
        self.num_applications += discount['freq']
        self.total_discount += discount['discount']
        self.num_orders += 1
        self.save()
    record_usage.alters_data = True

    def availability_description(self):
        """
        Return a description of when this offer is available
        """
        restrictions = self.availability_restrictions()
        descriptions = [r['description'] for r in restrictions]
        return "<br/>".join(descriptions)

    def availability_restrictions(self):  # noqa (too complex (15))
        restrictions = []
        if self.is_suspended:
            restrictions.append({
                'description': _("Offer is suspended"),
                'is_satisfied': False})

        if self.max_global_applications:
            remaining = self.max_global_applications - self.num_applications
            desc = _("Limited to %(total)d uses (%(remainder)d remaining)") \
                % {'total': self.max_global_applications,
                   'remainder': remaining}
            restrictions.append({'description': desc,
                                 'is_satisfied': remaining > 0})

        if self.max_user_applications:
            if self.max_user_applications == 1:
                desc = _("Limited to 1 use per user")
            else:
                desc = _("Limited to %(total)d uses per user") \
                    % {'total': self.max_user_applications}
            restrictions.append({'description': desc,
                                 'is_satisfied': True})

        if self.max_basket_applications:
            if self.max_user_applications == 1:
                desc = _("Limited to 1 use per basket")
            else:
                desc = _("Limited to %(total)d uses per basket") \
                    % {'total': self.max_basket_applications}
            restrictions.append({
                'description': desc,
                'is_satisfied': True})

        def hide_time_if_zero(dt):
            # Only show hours/minutes if they have been specified
            if dt.tzinfo:
                localtime = dt.astimezone(get_current_timezone())
            else:
                localtime = dt
            if localtime.hour == 0 and localtime.minute == 0:
                return date_filter(localtime, settings.DATE_FORMAT)
            return date_filter(localtime, settings.DATETIME_FORMAT)

        if self.start_datetime or self.end_datetime:
            today = now()
            if self.start_datetime and self.end_datetime:
                desc = _("Available between %(start)s and %(end)s") \
                    % {'start': hide_time_if_zero(self.start_datetime),
                       'end': hide_time_if_zero(self.end_datetime)}
                is_satisfied \
                    = self.start_datetime <= today <= self.end_datetime
            elif self.start_datetime:
                desc = _("Available from %(start)s") % {
                    'start': hide_time_if_zero(self.start_datetime)}
                is_satisfied = today >= self.start_datetime
            elif self.end_datetime:
                desc = _("Available until %(end)s") % {
                    'end': hide_time_if_zero(self.end_datetime)}
                is_satisfied = today <= self.end_datetime
            restrictions.append({
                'description': desc,
                'is_satisfied': is_satisfied})

        if self.max_discount:
            desc = _("Limited to a cost of %(max)s") % {
                'max': currency(self.max_discount)}
            restrictions.append({
                'description': desc,
                'is_satisfied': self.total_discount < self.max_discount})

        return restrictions

    @property
    def has_products(self):
        return self.condition.range is not None

    def products(self):
        """
        Return a queryset of products in this offer
        """
        Product = get_model('catalogue', 'Product')
        if not self.has_products:
            return Product.objects.none()

        queryset = self.condition.range.all_products()
        return queryset.filter(is_discountable=True).exclude(
            structure=Product.CHILD)
Ejemplo n.º 5
0
class MailActions(Basemodel):
    value = models.BooleanField(default=False, verbose_name='是否发送')
    desc_cn = models.CharField(max_length=128, null=True, blank=True)
Ejemplo n.º 6
0
class Agenda(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField(null=True,blank=True)
    editors = models.ManyToManyField('auth.User', related_name='agendas')
    votes = models.ManyToManyField('laws.Vote',through=AgendaVote)
    public_owner_name = models.CharField(max_length=100)
    is_public = models.BooleanField(default=False)
    num_followers = models.IntegerField(default=0)
    image = models.ImageField(blank=True, null=True, upload_to='agendas')

    objects = AgendaManager()

    class Meta:
        verbose_name = _('Agenda')
        verbose_name_plural = _('Agendas')
        unique_together = (("name", "public_owner_name"),)

    def __unicode__(self):
        return u"%s %s %s" % (self.name,_('edited by'),self.public_owner_name)

    @models.permalink
    def get_absolute_url(self):
        return ('agenda-detail', [str(self.id)])

    @models.permalink
    def get_edit_absolute_url(self):
        return ('agenda-detail-edit', [str(self.id)])

    def member_score(self, member):
        # Find all votes that
        #   1) This agenda is ascribed to
        #   2) the member participated in and either voted for or against
        qs = AgendaVote.objects.filter(
            agenda = self,
            vote__voteaction__member = member,
            vote__voteaction__type__in=['for','against']).extra(
                select={'weighted_score':'agendas_agendavote.score*agendas_agendavote.importance'}
            ).values_list('weighted_score','vote__voteaction__type')

        for_score = against_score = 0
        for score, action_type in qs:
            if action_type == 'against':
                against_score += score
            else:
                for_score += score

        max_score = sum([abs(x.score*x.importance) for x in
                         self.agendavotes.all()])
        if max_score > 0:
            return (for_score - against_score) / max_score * 100
        else:
            return 0.0

    def party_score(self, party):
        # Since we're already calculating python side, no need to do 2 queries
        # with joins, select for and against, and calcualte the things
        qs = AgendaVote.objects.filter(
            agenda=self, vote__voteaction__member__in=party.members.all(),
            vote__voteaction__type__in=['against', 'for']).extra(
                select={'weighted_score': 'agendas_agendavote.score*agendas_agendavote.importance'}
            ).values_list('weighted_score', 'vote__voteaction__type')

        for_score = 0
        against_score = 0

        for score, action_type in qs:
            if action_type == 'against':
                against_score += score
            else:
                for_score += score

        #max_score = sum([abs(x) for x in self.agendavotes.values_list('score', flat=True)]) * party.members.count()
        # To save the queries, make sure to pass prefetch/select related
        # Removed the values call, so that we can utilize the prefetched stuf
        # This reduces the number of queries when called for example from
        # AgendaResource.dehydrate
        max_score = sum(abs(x.score * x.importance) for x in
                        self.agendavotes.all()) * party.number_of_seats

        if max_score > 0:
            return (for_score - against_score) / max_score * 100
        else:
            return 0.0

    def candidate_list_score(self, candidate_list):
        # Since we're already calculating python side, no need to do 2 queries
        # with joins, select for and against, and calcualte the things
        qs = AgendaVote.objects.filter(
            agenda=self, vote__voteaction__member__in=candidate_list.member_ids,
            vote__voteaction__type__in=['against', 'for']).extra(
                select={'weighted_score': 'agendas_agendavote.score*agendas_agendavote.importance'}
            ).values_list('weighted_score', 'vote__voteaction__type')

        for_score = 0
        against_score = 0

        for score, action_type in qs:
            if action_type == 'against':
                against_score += score
            else:
                for_score += score

        #max_score = sum([abs(x) for x in self.agendavotes.values_list('score', flat=True)]) * party.members.count()
        # To save the queries, make sure to pass prefetch/select related
        # Removed the values call, so that we can utilize the prefetched stuf
        # This reduces the number of queries when called for example from
        # AgendaResource.dehydrate
        max_score = sum(abs(x.score * x.importance) for x in
                        self.agendavotes.all()) * len(candidate_list.member_ids)

        if max_score > 0:
            return (for_score - against_score) / max_score * 100
        else:
            return 0.0

    def related_mk_votes(self,member):
        # Find all votes that
        #   1) This agenda is ascribed to
        #   2) the member participated in and either voted for or against
        # for_votes      = AgendaVote.objects.filter(agenda=self,vote__voteaction__member=member,vote__voteaction__type="for").distinct()
        #against_votes   = AgendaVote.objects.filter(agenda=self,vote__voteaction__member=member,vote__voteaction__type="against").distinct()
        vote_actions = VoteAction.objects.filter(member=member,vote__agendavotes__agenda=self)
        all_votes = AgendaVote.objects.filter(agenda=self,vote__voteaction__member=member).distinct()
        # TODO: improve ugly code below
        member_votes = list()
        for member_vote in all_votes:
            for vote_action in vote_actions:
                if (vote_action.vote == member_vote.vote):
                    member_votes.insert(0,member_vote)
                    member_votes[0].voteaction = vote_action

        return member_votes
        #return AgendaVote.objects.filter(agenda=self,vote__voteaction__member=mk).distinct()

    def selected_instances(self, cls, top=3, bottom=3):
        instances = list(cls.objects.all())
        for instance in instances:
            instance.score = self.__getattribute__('%s_score' % instance.__class__.__name__.lower())(instance)
        instances.sort(key=attrgetter('score'))
        instances = get_top_bottom(instances, top, bottom)
        instances['top'].sort(key=attrgetter('score'), reverse=True)
        instances['bottom'].sort(key=attrgetter('score'), reverse=True)
        return instances

    def get_mks_values(self, knesset_number=None):
        """Return mks values.

        :param knesset_number: The knesset numer of the mks. ``None`` will
                               return current knesset (default: ``None``).
        """
        mks_grade = Agenda.objects.get_mks_values()

        if knesset_number is None:
            knesset = Knesset.objects.current_knesset()
        else:
            knesset = Knesset.objects.get(pk=knesset_number)

        mks_ids = Member.objects.filter(
            current_party__knesset=knesset).values_list('pk', flat=True)

        grades = mks_grade.get(self.id, [])
        current_grades = [x for x in grades if x[0] in mks_ids]
        return current_grades

    def get_mks_totals(self, member):
        "Get count for each vote type for a specific member on this agenda"

        # let's split qs to make it more readable
        qs = VoteAction.objects.filter(member=member, type__in=('for', 'against'), vote__agendavotes__agenda=self)
        qs = list(qs.values('type').annotate(total=Count('id')))

        totals = sum(x['total'] for x in qs)
        qs.append({'type': 'no-vote', 'total': self.votes.count() - totals})

        return qs

    def get_party_values(self, knesset_number=None):
        """Return party values.

        :param knesset_number: The knesset numer of the parties. ``None`` will
                               return current knesset (default: ``None``).
        """
        party_grades = Agenda.objects.get_all_party_values()
        all_grades = party_grades.get(self.id, [])

        if knesset_number is None:
            knesset = Knesset.objects.current_knesset()
        else:
            knesset = Knesset.objects.get(pk=knesset_number)

        current_parties_id = [x.pk for x in Party.objects.filter(knesset=knesset)]
        current_grades = [x for x in all_grades if x[0] in current_parties_id]
        return current_grades

    def get_all_party_values(self, knesset_number=None):
        if knesset_number is None:
            knesset = Knesset.objects.current_knesset()
        else:
            knesset = Knesset.objects.get(pk=knesset_number)

        current_parties_id = [x.pk for x in Party.objects.filter(knesset=knesset)]

        current_parties_scores = {}

        for agenda_id, parties_scores in Agenda.objects.get_all_party_values().iteritems():
            current_parties_scores[agenda_id] = [
                x for x in parties_scores if x[0] in current_parties_id]

        return current_parties_scores

    def get_suggested_votes_by_agendas(self, num):
        votes = Vote.objects.filter(~Q(agendavotes__agenda=self))
        votes = votes.annotate(score=Sum('agendavotes__importance'))
        return votes.order_by('-score')[:num]

    def get_suggested_votes_by_agenda_tags(self, num):
        # TODO: This is untested, agendas currently don't have tags
        votes = Vote.objects.filter(~Q(agendavotes__agenda=self))
        tag_importance_subquery = """
        SELECT sum(av.importance)
        FROM agendas_agendavote av
        JOIN tagging_taggeditem avti ON avti.object_id=av.id and avti.object_type_id=%s
        JOIN tagging_taggeditem ati ON ati.object_id=agendas_agenda.id and ati.object_type_id=%s
        WHERE avti.tag_id = ati.tag_id
        """
        agenda_type_id = ContentType.objects.get_for_model(self).id
        votes = votes.extra(select=dict(score = tag_importance_subquery),
                            select_params = [agenda_type_id]*2)
        return votes.order_by('-score')[:num]

    def get_suggested_votes_by_controversy(self, num):
        votes = Vote.objects.filter(~Q(agendavotes__agenda=self))
        votes = votes.extra(select=dict(score = 'controversy'))
        return votes.order_by('-score')[:num]
Ejemplo n.º 7
0
class Snippet(CachingMixin, models.Model):
    name = models.CharField(max_length=255, unique=True)
    template = models.ForeignKey(SnippetTemplate)
    data = models.TextField(default='{}', validators=[validate_xml])

    priority = models.IntegerField(default=0, blank=True)
    disabled = models.BooleanField(default=True)

    country = CountryField('Geolocation Country', blank=True, default='')

    publish_start = models.DateTimeField(blank=True, null=True)
    publish_end = models.DateTimeField(blank=True, null=True)

    on_release = models.BooleanField(default=True, verbose_name='Release')
    on_beta = models.BooleanField(default=False, verbose_name='Beta')
    on_aurora = models.BooleanField(default=False, verbose_name='Aurora')
    on_nightly = models.BooleanField(default=False, verbose_name='Nightly')

    on_startpage_1 = models.BooleanField(default=False, verbose_name='Version 1')
    on_startpage_2 = models.BooleanField(default=True, verbose_name='Version 2')
    on_startpage_3 = models.BooleanField(default=True, verbose_name='Version 3')
    on_startpage_4 = models.BooleanField(default=True, verbose_name='Version 4')

    weight = models.IntegerField(
        'Prevalence', choices=SNIPPET_WEIGHTS, default=100,
        help_text='How often should this snippet be shown to users?')

    client_match_rules = models.ManyToManyField(
        ClientMatchRule, blank=True, verbose_name='Client Match Rules')

    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    objects = models.Manager()
    cached_objects = SnippetManager()

    class Meta:
        ordering = ('-modified',)

    def render(self):
        data = json.loads(self.data)
        if self.id:
            data.setdefault('snippet_id', self.id)

        # Use a list for attrs to make the output order predictable.
        attrs = [('data-snippet-id', self.id),
                 ('data-weight', self.weight)]
        if self.country:
            attrs.append(('data-country', self.country))
        attr_string = ' '.join('{0}="{1}"'.format(key, value) for key, value in
                               attrs)

        rendered_snippet = u'<div {attrs}>{content}</div>'.format(
            attrs=attr_string,
            content=self.template.render(data)
        )

        return Markup(rendered_snippet)

    @property
    def channels(self):
        channels = []
        for channel in CHANNELS:
            if getattr(self, 'on_{0}'.format(channel), False):
                channels.append(channel)
        return channels

    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('base.show', kwargs={'snippet_id': self.id})
Ejemplo n.º 8
0
class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Category',
            fields=[
                ('id', models.IntegerField(db_column='cat_id', primary_key=True, serialize=False)),
                ('title', models.CharField(db_column='cat_title', max_length=255)),
            ],
            options={
                'verbose_name': 'MediaWiki Category',
                'verbose_name_plural': 'MediaWiki Categories',
                'db_table': 'category',
                'ordering': ['title'],
            },
        ),
        migrations.CreateModel(
            name='CategoryLink',
            fields=[
                ('id', models.IntegerField(db_column='cl_sortkey', primary_key=True, serialize=False)),
                ('cat', models.CharField(db_column='cl_to', max_length=255)),
            ],
            options={
                'verbose_name': 'MediaWiki Category Link',
                'verbose_name_plural': 'MediaWiki Category Links',
                'db_table': 'categorylinks',
                'ordering': ['cat', 'page'],
            },
        ),
        migrations.CreateModel(
            name='Page',
            fields=[
                ('id', models.IntegerField(db_column='page_id', primary_key=True, serialize=False)),
                ('namespace', models.IntegerField(db_column='page_namespace')),
                ('title_url', models.CharField(db_column='page_title', max_length=255)),
                ('len', models.IntegerField(db_column='page_len')),
                ('is_redirect', models.BooleanField(db_column='page_is_redirect', default=False)),
            ],
            options={
                'verbose_name': 'MediaWiki Page',
                'verbose_name_plural': 'MediaWiki Pages',
                'db_table': 'page',
                'ordering': ['namespace', 'title_url'],
            },
        ),
        migrations.CreateModel(
            name='Revision',
            fields=[
                ('id', models.IntegerField(db_column='rev_id', primary_key=True, serialize=False)),
                ('timestamp', models.CharField(db_column='rev_timestamp', max_length=14)),
                ('page', models.ForeignKey(db_column='rev_page', on_delete=django.db.models.deletion.PROTECT, related_name='+', to='compat.Page')),
            ],
            options={
                'verbose_name': 'MediaWiki Revision',
                'verbose_name_plural': 'MediaWiki Revisions',
                'db_table': 'revision',
            },
        ),
        migrations.CreateModel(
            name='Text',
            fields=[
                ('id', models.IntegerField(db_column='old_id', primary_key=True, serialize=False)),
                ('data_raw', models.TextField(db_column='old_text')),
            ],
            options={
                'verbose_name': 'MediaWiki Text Blob',
                'verbose_name_plural': 'MediaWiki Text Blobs',
                'db_table': 'pagecontent',
            },
        ),
        migrations.AddField(
            model_name='revision',
            name='text',
            field=models.ForeignKey(db_column='rev_text_id', on_delete=django.db.models.deletion.PROTECT, related_name='+', to='compat.Text'),
        ),
        migrations.AddField(
            model_name='page',
            name='latest',
            field=models.ForeignKey(db_column='page_latest', on_delete=django.db.models.deletion.PROTECT, related_name='+', to='compat.Revision'),
        ),
        migrations.AddField(
            model_name='categorylink',
            name='page',
            field=models.ForeignKey(db_column='cl_from', on_delete=django.db.models.deletion.PROTECT, related_name='+', to='compat.Page'),
        ),
    ]
Ejemplo n.º 9
0
class ServiceEventReviewNotice(models.Model):

    UNREVIEWED = 0

    NOTIFICATION_TYPES = (
        (UNREVIEWED, _l("Notify about Service Events awaiting review")),
    )

    TIME_CHOICES = [(dt_time(x // 60, x % 60), "%02d:%02d" % (x // 60, x % 60)) for x in range(0, 24 * 60, 15)]

    notification_type = models.IntegerField(
        verbose_name=_l("Notification Type"),
        choices=NOTIFICATION_TYPES,
        default=UNREVIEWED,
    )

    send_empty = models.BooleanField(
        verbose_name=_l("Send Empty Notices"),
        help_text=_l("Check to send notices even if there's no unreviewed Service Events to currently notify about"),
        default=False,
    )

    recurrences = RecurrenceField(
        verbose_name=_l("Recurrences"),
        help_text=_l("Define the schedule this notification should be sent on."),
        default="",
    )

    time = models.TimeField(
        verbose_name=_l("Time of day"),
        help_text=_l(
            "Set the time of day this notice should be sent (00:00-23:59)."
        ),
        choices=TIME_CHOICES,
    )

    recipients = models.ForeignKey(
        RecipientGroup,
        verbose_name=_l("Recipients"),
        help_text=_l("Choose the group of recipients who should receive these notifications"),
        on_delete=models.PROTECT,
    )

    units = models.ForeignKey(
        UnitGroup,
        verbose_name=_l("Unit Group filter"),
        help_text=_l(
            "Select which group of Units this notification should be limited to. Leave blank to include all units"
        ),
        null=True,
        blank=True,
        on_delete=models.PROTECT,
    )

    last_sent = models.DateTimeField(null=True, editable=False)

    class Meta:
        verbose_name = _l("Service Event Review Notice")

    @property
    def is_unreviewed(self):
        return self.notification_type == self.UNREVIEWED

    def ses(self):
        """Return TestListInstances relevant to this notice"""

        ses = ServiceEvent.objects.review_required()

        if self.units_id:
            ses = ses.filter(unit_service_area__unit__in=self.units.units.all())

        return ses.order_by(
            "unit_service_area__unit__%s" % settings.ORDER_UNITS_BY,
            "unit_service_area__service_area__name",
        )

    def ses_by_unit_usa(self):

        ses = self.ses()
        return ses.values(
            "unit_service_area__unit__name",
            "unit_service_area__service_area__name",
        ).order_by(
            "unit_service_area__unit__name",
            "unit_service_area__service_area__name",
        ).annotate(
            Count("unit_service_area__unit__name"),
            Count("unit_service_area__service_area__name"),
        )

    def send_required(self):
        return self.send_empty or self.ses().count() > 0
class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ("contacts", "0003_auto_20190305_0809"),
        ("invoices", "0003_auto_20190304_2247"),
    ]

    operations = [
        migrations.CreateModel(
            name="RecurringInvoice",
            fields=[
                (
                    "id",
                    models.AutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                (
                    "subtotal",
                    models.DecimalField(
                        decimal_places=2,
                        default=Decimal("0.00"),
                        max_digits=10,
                        validators=[django.core.validators.MinValueValidator(0)],
                        verbose_name="subtotal",
                    ),
                ),
                (
                    "discount",
                    models.DecimalField(
                        decimal_places=2,
                        default=Decimal("0.00"),
                        max_digits=10,
                        validators=[django.core.validators.MinValueValidator(0)],
                        verbose_name="discount",
                    ),
                ),
                (
                    "liable_to_vat",
                    models.BooleanField(
                        default=True,
                        help_text="For example invoices to foreign institutions are not liable to VAT.",
                        verbose_name="liable to VAT",
                    ),
                ),
                (
                    "tax_rate",
                    models.DecimalField(
                        decimal_places=2,
                        default=Decimal("7.7"),
                        max_digits=10,
                        validators=[django.core.validators.MinValueValidator(0)],
                        verbose_name="tax rate",
                    ),
                ),
                (
                    "total",
                    models.DecimalField(
                        decimal_places=2,
                        default=Decimal("0.00"),
                        max_digits=10,
                        validators=[django.core.validators.MinValueValidator(0)],
                        verbose_name="total",
                    ),
                ),
                ("title", models.CharField(max_length=200, verbose_name="title")),
                (
                    "description",
                    models.TextField(blank=True, verbose_name="description"),
                ),
                (
                    "created_at",
                    models.DateTimeField(
                        default=django.utils.timezone.now, verbose_name="created at"
                    ),
                ),
                ("postal_address", models.TextField(verbose_name="postal address")),
                (
                    "starts_on",
                    models.DateField(
                        default=datetime.date.today, verbose_name="starts on"
                    ),
                ),
                (
                    "ends_on",
                    models.DateField(blank=True, null=True, verbose_name="ends on"),
                ),
                (
                    "periodicity",
                    models.CharField(
                        choices=[
                            ("yearly", "yearly"),
                            ("quarterly", "quarterly"),
                            ("monthly", "monthly"),
                            ("weekly", "weekly"),
                        ],
                        max_length=20,
                        verbose_name="periodicity",
                    ),
                ),
                (
                    "next_period_starts_on",
                    models.DateField(
                        blank=True, null=True, verbose_name="next period starts on"
                    ),
                ),
                (
                    "contact",
                    models.ForeignKey(
                        blank=True,
                        null=True,
                        on_delete=django.db.models.deletion.SET_NULL,
                        to="contacts.Person",
                        verbose_name="contact",
                    ),
                ),
                (
                    "customer",
                    models.ForeignKey(
                        on_delete=django.db.models.deletion.PROTECT,
                        to="contacts.Organization",
                        verbose_name="customer",
                    ),
                ),
                (
                    "owned_by",
                    models.ForeignKey(
                        on_delete=django.db.models.deletion.PROTECT,
                        to=settings.AUTH_USER_MODEL,
                        verbose_name="responsible",
                    ),
                ),
            ],
            options={
                "verbose_name": "recurring invoice",
                "verbose_name_plural": "recurring invoices",
                "ordering": ["customer__name", "title"],
            },
        ),
        migrations.RunSQL("SELECT audit_audit_table('invoices_recurringinvoice');", ""),
    ]
Ejemplo n.º 11
0
class Migration(migrations.Migration):

    dependencies = [
        ('RecipeExt', '0003_ingredient'),
    ]

    operations = [
        migrations.CreateModel(
            name='Recipe',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('title', models.CharField(max_length=50)),
                ('directions', models.CharField(max_length=5000)),
                ('prep_time', models.DurationField()),
                ('cook_time', models.DurationField()),
                ('total_time', models.DurationField()),
                ('serving_size', models.IntegerField(default=1)),
                ('nutritional_info', models.CharField(max_length=200)),
                ('thumbnail_url', models.URLField(max_length=100)),
                ('source', models.URLField(max_length=100)),
            ],
            options={
                'ordering': ('title', ),
            },
        ),
        migrations.AlterField(
            model_name='chef',
            name='email',
            field=models.CharField(max_length=50, unique=True),
        ),
        migrations.AlterField(
            model_name='ingredient',
            name='name',
            field=models.CharField(max_length=50, unique=True),
        ),
        migrations.CreateModel(
            name='RecipeIngredient',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('ingredient_string', models.CharField(max_length=50)),
                ('available', models.BooleanField(default=True)),
                ('ingredient',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='RecipeExt.ingredient')),
                ('recipe',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='RecipeExt.recipe')),
            ],
            options={
                'ordering': ('recipe', 'ingredient'),
            },
        ),
        migrations.AddField(
            model_name='recipe',
            name='author',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='RecipeExt.chef'),
        ),
        migrations.AddField(
            model_name='recipe',
            name='ingredients',
            field=models.ManyToManyField(through='RecipeExt.RecipeIngredient',
                                         to='RecipeExt.Ingredient'),
        ),
    ]
Ejemplo n.º 12
0
class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='alumno',
            fields=[
                ('n_control',
                 models.CharField(max_length=8,
                                  serialize=False,
                                  primary_key=True)),
                ('nombre', models.CharField(max_length=64)),
                ('apellido', models.CharField(max_length=64)),
                ('correo', models.EmailField(max_length=254)),
                ('categoria',
                 models.CharField(default=b'estudiante', max_length=64)),
                ('user_perfil',
                 models.OneToOneField(related_name='alumno',
                                      to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='alumno_materia',
            fields=[
                ('id', models.AutoField(serialize=False, primary_key=True)),
                ('alum',
                 models.ForeignKey(related_name='alumno',
                                   to='app_examen.alumno')),
            ],
        ),
        migrations.CreateModel(
            name='examen',
            fields=[
                ('id_examen',
                 models.AutoField(serialize=False, primary_key=True)),
                ('unidad', models.IntegerField()),
                ('id_alumno',
                 models.ForeignKey(blank=True,
                                   to='app_examen.alumno',
                                   null=True)),
            ],
        ),
        migrations.CreateModel(
            name='maestro',
            fields=[
                ('n_empleado',
                 models.CharField(max_length=64,
                                  serialize=False,
                                  primary_key=True)),
                ('nombre', models.CharField(max_length=64)),
                ('correo', models.EmailField(max_length=254)),
                ('categoria',
                 models.CharField(default=b'maestros',
                                  max_length=64,
                                  null=True)),
                ('user_perfil',
                 models.OneToOneField(related_name='profile',
                                      to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='materia',
            fields=[
                ('serie',
                 models.SlugField(max_length=64,
                                  serialize=False,
                                  primary_key=True)),
                ('nombre', models.CharField(max_length=64)),
                ('maestro_a',
                 models.ForeignKey(related_name='maestro_inparte',
                                   to='app_examen.maestro',
                                   max_length=64)),
            ],
        ),
        migrations.CreateModel(
            name='pregunta',
            fields=[
                ('id', models.AutoField(serialize=False, primary_key=True)),
                ('nombre', models.CharField(max_length=64)),
                ('semestre', models.IntegerField()),
                ('dificultad',
                 models.CharField(max_length=64,
                                  choices=[(b'Facil', b'Facil'),
                                           (b'Intermedio', b'Intermedio'),
                                           (b'Dificil', b'Dificil')])),
                ('valor',
                 models.PositiveIntegerField(validators=[
                     django.core.validators.MinValueValidator(1),
                     django.core.validators.MaxValueValidator(100)
                 ])),
                ('materia',
                 models.ForeignKey(related_name='mat',
                                   to='app_examen.materia')),
            ],
        ),
        migrations.CreateModel(
            name='pregunta_respuesta',
            fields=[
                ('id_pregunta_respuesta',
                 models.AutoField(serialize=False, primary_key=True)),
                ('id_pregunta', models.ForeignKey(to='app_examen.pregunta')),
            ],
        ),
        migrations.CreateModel(
            name='respuesta',
            fields=[
                ('id', models.AutoField(serialize=False, primary_key=True)),
                ('nombre', models.CharField(max_length=64)),
                ('correcta', models.BooleanField()),
                ('pregun',
                 models.ForeignKey(related_name='pregunt',
                                   to='app_examen.pregunta')),
            ],
        ),
        migrations.AddField(
            model_name='pregunta_respuesta',
            name='id_respuesta',
            field=models.ManyToManyField(to='app_examen.respuesta'),
        ),
        migrations.AddField(
            model_name='examen',
            name='id_materia',
            field=models.ForeignKey(related_name='idmate',
                                    to='app_examen.materia'),
        ),
        migrations.AddField(
            model_name='examen',
            name='id_pregunta_respuesta',
            field=models.ManyToManyField(to='app_examen.pregunta_respuesta'),
        ),
        migrations.AddField(
            model_name='alumno_materia',
            name='materi',
            field=models.ForeignKey(related_name='materia',
                                    to='app_examen.materia'),
        ),
        migrations.AlterUniqueTogether(
            name='examen',
            unique_together=set([('id_materia', 'unidad')]),
        ),
        migrations.AlterUniqueTogether(
            name='alumno_materia',
            unique_together=set([('alum', 'materi')]),
        ),
    ]
Ejemplo n.º 13
0
class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Base',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('modified', models.DateTimeField(auto_now=True)),
                ('created_by',
                 models.ForeignKey(
                     blank=True,
                     null=True,
                     on_delete=django.db.models.deletion.SET_NULL,
                     related_name='basecreated',
                     to=settings.AUTH_USER_MODEL)),
                ('modified_by',
                 models.ForeignKey(
                     blank=True,
                     null=True,
                     on_delete=django.db.models.deletion.SET_NULL,
                     related_name='basemodified',
                     to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='Category',
            fields=[
                ('base_ptr',
                 models.OneToOneField(
                     auto_created=True,
                     on_delete=django.db.models.deletion.CASCADE,
                     parent_link=True,
                     primary_key=True,
                     serialize=False,
                     to='tasks.base')),
                ('name', models.CharField(max_length=100)),
            ],
            bases=('tasks.base', ),
        ),
        migrations.CreateModel(
            name='Tasks',
            fields=[
                ('base_ptr',
                 models.OneToOneField(
                     auto_created=True,
                     on_delete=django.db.models.deletion.CASCADE,
                     parent_link=True,
                     primary_key=True,
                     serialize=False,
                     to='tasks.base')),
                ('name', models.TextField()),
                ('is_completed', models.BooleanField(default=False)),
                ('task_category',
                 models.ForeignKey(blank=True,
                                   null=True,
                                   on_delete=django.db.models.deletion.CASCADE,
                                   to='tasks.category')),
            ],
            bases=('tasks.base', ),
        ),
    ]
Ejemplo n.º 14
0
class Migration(migrations.Migration):

    initial = True

    dependencies = []

    operations = [
        migrations.CreateModel(
            name='User',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('password',
                 models.CharField(max_length=128, verbose_name='password')),
                ('first_name', models.CharField(max_length=30)),
                ('last_name', models.CharField(max_length=150)),
                ('username', models.CharField(max_length=50, unique=True)),
                ('email', models.EmailField(max_length=254, unique=True)),
                ('gender',
                 models.CharField(choices=[('M', 'Male'), ('F', 'Female'),
                                           ('O', 'Others')],
                                  max_length=1)),
                ('phone_number',
                 models.CharField(blank=True,
                                  max_length=15,
                                  null=True,
                                  unique=True)),
                ('country',
                 models.CharField(blank=True, max_length=20, null=True)),
                ('referrer',
                 models.CharField(blank=True, max_length=20, null=True)),
                ('ref_id',
                 models.CharField(blank=True,
                                  max_length=20,
                                  null=True,
                                  unique=True)),
                ('email_confirmed', models.BooleanField(default=False)),
                ('registered_on', models.DateTimeField(auto_now_add=True)),
                ('last_login', models.DateTimeField(auto_now=True)),
                ('is_admin', models.BooleanField(default=False)),
                ('is_active', models.BooleanField(default=True)),
                ('is_staff', models.BooleanField(default=False)),
                ('is_superuser', models.BooleanField(default=False)),
            ],
            options={
                'abstract': False,
            },
            managers=[
                ('object', django.db.models.manager.Manager()),
            ],
        ),
        migrations.CreateModel(
            name='AllEarnings',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('amount',
                 models.DecimalField(blank=True,
                                     decimal_places=2,
                                     max_digits=19,
                                     null=True)),
                ('date_earned', models.DateTimeField(auto_now=True)),
            ],
        ),
        migrations.CreateModel(
            name='LoginBonus',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('amount',
                 models.DecimalField(decimal_places=2,
                                     max_digits=19,
                                     null=True)),
            ],
            options={
                'verbose_name_plural': 'Login Bonus',
            },
        ),
        migrations.CreateModel(
            name='PremiumLoginBonus',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('amount',
                 models.DecimalField(decimal_places=2,
                                     max_digits=19,
                                     null=True)),
            ],
            options={
                'verbose_name_plural': 'Premium User Login Bonus',
            },
        ),
        migrations.CreateModel(
            name='PremiumReferBonus',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('amount',
                 models.DecimalField(decimal_places=2,
                                     max_digits=19,
                                     null=True)),
            ],
            options={
                'verbose_name_plural': 'Premium User Refer Bonus',
            },
        ),
        migrations.CreateModel(
            name='PremiumUser',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('upgrade_on', models.DateTimeField(auto_now=True)),
            ],
            options={
                'verbose_name_plural': 'Premium Users',
            },
        ),
        migrations.CreateModel(
            name='ReferBonus',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('amount',
                 models.DecimalField(decimal_places=2,
                                     max_digits=19,
                                     null=True)),
            ],
            options={
                'verbose_name_plural': 'Refer Bonus',
            },
        ),
        migrations.CreateModel(
            name='SignupBonus',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('amount',
                 models.DecimalField(decimal_places=2,
                                     max_digits=19,
                                     null=True)),
            ],
            options={
                'verbose_name_plural': 'Signup Bonus',
            },
        ),
        migrations.CreateModel(
            name='Upgrade',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('name', models.CharField(blank=True, max_length=50,
                                          null=True)),
                ('price',
                 models.DecimalField(decimal_places=2,
                                     max_digits=19,
                                     null=True)),
            ],
            options={
                'verbose_name_plural': 'Upgrade',
            },
        ),
        migrations.CreateModel(
            name='WithdrawRequest',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('amount',
                 models.DecimalField(blank=True,
                                     decimal_places=2,
                                     max_digits=19,
                                     null=True)),
                ('bank_name',
                 models.CharField(blank=True, max_length=50, null=True)),
                ('account_number',
                 models.CharField(blank=True, max_length=50, null=True)),
                ('status', models.BooleanField(default=False)),
                ('request_on', models.DateTimeField(auto_now=True)),
                ('user',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'verbose_name_plural': 'Withdraw Requests',
            },
        ),
        migrations.CreateModel(
            name='Wallet',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('balance',
                 models.DecimalField(decimal_places=2,
                                     max_digits=19,
                                     null=True)),
                ('user',
                 models.OneToOneField(
                     on_delete=django.db.models.deletion.CASCADE,
                     to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'verbose_name_plural': 'User Wallets',
            },
        ),
        migrations.CreateModel(
            name='UserLogins',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('date', models.DateTimeField(auto_now=True)),
                ('user',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'verbose_name_plural': 'User Logins',
            },
        ),
        migrations.AddConstraint(
            model_name='upgrade',
            constraint=models.UniqueConstraint(fields=('name', 'price'),
                                               name='premium_package'),
        ),
        migrations.AddField(
            model_name='premiumuser',
            name='user',
            field=models.OneToOneField(
                on_delete=django.db.models.deletion.CASCADE,
                to=settings.AUTH_USER_MODEL),
        ),
        migrations.AddField(
            model_name='allearnings',
            name='user',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to=settings.AUTH_USER_MODEL),
        ),
        migrations.AddConstraint(
            model_name='wallet',
            constraint=models.UniqueConstraint(fields=('user', 'balance'),
                                               name='user_wallet'),
        ),
    ]
Ejemplo n.º 15
0
class PublicBarrier(FullyArchivableMixin, BaseModel):
    """
    Public barriers are the representation of a barrier (as the name suggests) to the public.
    This table should not be exposed to the public however only to the DMAS frontend which requires login.
    Transfer the data to a flat file or another service which can safely expose the data.
    """
    id = HashidAutoField(primary_key=True,
                         min_length=6,
                         alphabet="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    barrier = models.OneToOneField(Barrier,
                                   on_delete=CASCADE,
                                   related_name="public_barrier")

    # === Title related fields =====
    _title = models.CharField(blank=True, max_length=MAX_LENGTH)
    title_updated_on = models.DateTimeField(null=True, blank=True)
    internal_title_at_update = models.CharField(blank=True,
                                                max_length=MAX_LENGTH)

    # === Summary related fields =====
    _summary = models.TextField(blank=True)
    summary_updated_on = models.DateTimeField(null=True, blank=True)
    internal_summary_at_update = models.TextField(blank=True,
                                                  max_length=MAX_LENGTH)

    # === Non editable fields ====
    status = models.PositiveIntegerField(choices=BarrierStatus.choices,
                                         default=0)
    status_date = models.DateField(blank=True, null=True)
    country = models.UUIDField(blank=True, null=True)
    # caused_by_country_trading_bloc = models.BooleanField(null=True)
    caused_by_trading_bloc = models.BooleanField(blank=True, null=True)
    trading_bloc = models.CharField(
        choices=TRADING_BLOC_CHOICES,
        max_length=7,
        blank=True,
    )
    sectors = ArrayField(models.UUIDField(),
                         blank=True,
                         null=False,
                         default=list)
    all_sectors = models.BooleanField(blank=True, null=True)
    categories = models.ManyToManyField(Category,
                                        related_name="public_barriers")

    published_versions = models.JSONField(default=dict)

    # === Status and timestamps ====
    _public_view_status = models.PositiveIntegerField(
        choices=PublicBarrierStatus.choices, default=0)
    first_published_on = models.DateTimeField(null=True, blank=True)
    last_published_on = models.DateTimeField(null=True, blank=True)
    unpublished_on = models.DateTimeField(null=True, blank=True)

    class Meta:
        permissions = [
            ('publish_barrier', 'Can publish barrier'),
            ('mark_barrier_as_ready_for_publishing',
             'Can mark barrier as ready for publishing'),
        ]

    def add_new_version(self):
        # self.published_versions structure:
        # {
        #     "latest_version": 3,
        #     "versions": {
        #         1: {
        #                "version": 1,
        #                "published_on: "datetime",
        #            },
        #         2: {...},
        #         3: {...}
        #     }
        # }
        latest_version = self.published_versions.get("latest_version", "0")
        new_version = str(int(latest_version) + 1)
        entry = {
            "version": new_version,
            "published_on": self.last_published_on.isoformat()
        }
        if not self.published_versions:
            self.published_versions = {"latest_version": "0", "versions": {}}
        self.published_versions["latest_version"] = new_version
        self.published_versions["versions"].setdefault(new_version, entry)

    def get_published_version(self, version):
        version = str(version)
        if self.published_versions:
            timestamp = self.published_versions["versions"][version][
                "published_on"]
            historic_public_barrier = self.history.as_of(
                datetime.datetime.fromisoformat(timestamp))
            return historic_public_barrier
        else:
            return None

    @property
    def latest_published_version(self):
        return self.get_published_version(
            self.published_versions.get("latest_version", 0))

    def update_non_editable_fields(self):
        self.status = self.internal_status
        self.status_date = self.internal_status_date
        self.country = self.internal_country
        # self.caused_by_country_trading_bloc = self.internal_caused_by_trading_bloc
        self.caused_by_trading_bloc = self.internal_caused_by_trading_bloc
        self.trading_bloc = self.internal_trading_bloc
        self.sectors = self.internal_sectors
        self.all_sectors = self.internal_all_sectors
        self.categories.set(self.internal_categories.all())

    def publish(self):
        if self.ready_to_be_published:
            self.update_non_editable_fields()
            self.unpublished_on = None
            self.public_view_status = PublicBarrierStatus.PUBLISHED
            self.add_new_version()
            self._history_date = self.last_published_on
            self.save()
            return True
        else:
            return False

    @property
    def title(self):
        return self._title

    @title.setter
    def title(self, value):
        self._title = value
        self.internal_title_at_update = self.barrier.title
        self.title_updated_on = timezone.now()

    @property
    def title_changed(self):
        if self.title:
            if self.latest_published_version:
                return self.title != self.latest_published_version.title
            else:
                return True
        else:
            return False

    @property
    def summary(self):
        return self._summary

    @summary.setter
    def summary(self, value):
        self._summary = value
        self.internal_summary_at_update = self.barrier.summary
        self.summary_updated_on = timezone.now()

    @property
    def summary_changed(self):
        if self.summary:
            if self.latest_published_version:
                return self.summary != self.latest_published_version.summary
            else:
                return True
        else:
            return False

    @property
    def location(self):
        return get_location_text(
            country_id=self.country,
            trading_bloc=self.trading_bloc,
            caused_by_trading_bloc=self.caused_by_trading_bloc,
        )

    @property
    def public_view_status(self):
        # set default if eligibility is avail on the internal barrier
        if (self._public_view_status == PublicBarrierStatus.UNKNOWN):
            if self.barrier.public_eligibility is True:
                self._public_view_status = PublicBarrierStatus.ELIGIBLE
            if self.barrier.public_eligibility is False:
                self._public_view_status = PublicBarrierStatus.INELIGIBLE

        # The internal barrier might get withdrawn from the public domain
        # in which case it will be marked as ineligible for public view
        # and the public barrier view status should update as well
        #
        # Note: cannot automatically change from published
        #       the public barrier would need to be unpublished first
        if self._public_view_status != PublicBarrierStatus.PUBLISHED:
            # Marking the public barrier ineligible
            if (self.barrier.public_eligibility is False
                    and self._public_view_status !=
                    PublicBarrierStatus.INELIGIBLE):
                self._public_view_status = PublicBarrierStatus.INELIGIBLE
                self.save()
            # Marking the public barrier eligible
            if (self.barrier.public_eligibility is True
                    and self._public_view_status
                    == PublicBarrierStatus.INELIGIBLE):
                self._public_view_status = PublicBarrierStatus.ELIGIBLE
                self.save()

        return self._public_view_status

    @public_view_status.setter
    def public_view_status(self, value):
        """ Set relevant date automatically """
        status = int(value)
        self._public_view_status = status
        # auto update date fields based on the new status
        now = timezone.now()
        if status == PublicBarrierStatus.PUBLISHED:
            self.first_published_on = self.first_published_on or now
            self.last_published_on = now
        if status == PublicBarrierStatus.UNPUBLISHED:
            self.unpublished_on = now

    @property
    def is_currently_published(self):
        """
        Is this barrier currently visible on the public frontend?
        """
        return self.first_published_on and not self.unpublished_on

    @property
    def internal_title_changed(self):
        if self.internal_title_at_update:
            return self.barrier.title != self.internal_title_at_update
        else:
            return False

    @property
    def internal_summary_changed(self):
        if self.internal_summary_at_update:
            return self.barrier.summary != self.internal_summary_at_update
        else:
            return False

    @property
    def internal_status(self):
        return self.barrier.status

    @property
    def internal_status_changed(self):
        return self.barrier.status != self.status

    @property
    def internal_status_date(self):
        return self.barrier.status_date

    @property
    def internal_status_date_changed(self):
        # Change in status date is only relevant if the barrier is resolved
        return ((self.internal_is_resolved or self.is_resolved)
                and (self.internal_status_date != self.status_date))

    @property
    def is_resolved(self):
        return self.status == BarrierStatus.RESOLVED_IN_FULL

    @property
    def internal_is_resolved(self):
        return self.barrier.is_resolved

    @property
    def internal_is_resolved_changed(self):
        return self.barrier.is_resolved != self.is_resolved

    @property
    def internal_country(self):
        return self.barrier.country

    @property
    def internal_country_changed(self):
        return self.barrier.country != self.country

    @property
    def internal_caused_by_trading_bloc(self):
        return self.barrier.caused_by_trading_bloc

    @property
    def internal_caused_by_trading_bloc_changed(self):
        # return self.barrier.caused_by_trading_bloc != self.caused_by_country_trading_bloc
        return self.barrier.caused_by_trading_bloc != self.caused_by_trading_bloc

    @property
    def internal_trading_bloc(self):
        return self.barrier.trading_bloc

    @property
    def internal_trading_bloc_changed(self):
        return self.barrier.trading_bloc != self.trading_bloc

    @property
    def internal_location(self):
        return get_location_text(
            country_id=self.barrier.country,
            trading_bloc=self.barrier.trading_bloc,
            caused_by_trading_bloc=self.barrier.caused_by_trading_bloc,
        )

    @property
    def internal_location_changed(self):
        return self.internal_location != self.location

    @property
    def internal_sectors(self):
        return self.barrier.sectors

    @property
    def internal_sectors_changed(self):
        return self.barrier.sectors != self.sectors

    @property
    def internal_all_sectors(self):
        return self.barrier.all_sectors

    @property
    def internal_all_sectors_changed(self):
        return self.barrier.all_sectors != self.all_sectors

    @property
    def internal_categories(self):
        return self.barrier.categories

    @property
    def internal_categories_changed(self):
        # TODO: consider other options
        return set(self.barrier.categories.all()) != set(self.categories.all())

    @property
    def internal_created_on(self):
        return self.barrier.created_on

    @property
    def ready_to_be_published(self):
        is_ready = self.public_view_status == PublicBarrierStatus.READY
        is_republish = self.unpublished_on is not None
        has_changes = self.unpublished_changes
        has_title_and_summary = bool(self.title and self.summary)
        return (is_ready and has_title_and_summary
                and (is_republish or has_changes))

    @property
    def unpublished_changes(self):
        return (self.title_changed or self.summary_changed
                or self.internal_is_resolved_changed
                or self.internal_status_date_changed
                or self.internal_location_changed
                or self.internal_sectors_changed
                or self.internal_all_sectors_changed
                or self.internal_sectors_changed
                or self.internal_categories_changed)

    history = HistoricalRecords(bases=[PublicBarrierHistoricalModel])
Ejemplo n.º 16
0
class UserToForum(models.Model):
    """用户关注模块表"""
    user = models.ForeignKey(UserInfo, on_delete=models.CASCADE)
    forum = models.ForeignKey(Forum, on_delete=models.CASCADE)
    status = models.BooleanField(default=True)
Ejemplo n.º 17
0
class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Baron_League_Rosters',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('acronym', models.CharField(max_length=4)),
                ('team_name', models.CharField(max_length=25)),
                ('wins', models.PositiveIntegerField(default=0)),
                ('losses', models.PositiveIntegerField(default=0)),
                ('tie_breaker', models.PositiveIntegerField(default=0)),
                ('is_active', models.BooleanField(default=True, help_text='This will change to false whenever the League is over.')),
                ('sub1_role', models.CharField(blank=True, choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], default='N/A', max_length=20)),
                ('sub2_role', models.CharField(blank=True, choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], default='N/A', max_length=20)),
                ('sub3_role', models.CharField(blank=True, choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], default='N/A', max_length=20)),
                ('coach', models.CharField(blank=True, max_length=32)),
            ],
            options={
                'verbose_name_plural': 'Baron Rosters',
                'db_table': 'Baron Rosters',
            },
        ),
        migrations.CreateModel(
            name='Baron_Match_Report',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('match_id', models.PositiveIntegerField(default=0)),
                ('did_blue_win', models.BooleanField(default=True, help_text='DOUBLE CHECK THIS')),
                ('week_number', models.PositiveIntegerField(default=1)),
                ('game_number', models.PositiveIntegerField(help_text="In BoX series, it's game number. Otherwise, game number for a given week")),
                ('match_time', models.DateTimeField(help_text='Put in your timezone')),
            ],
            options={
                'verbose_name_plural': 'Baron Match Reports',
                'db_table': 'Baron Match Report',
            },
        ),
        migrations.CreateModel(
            name='Baron_Players',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('summoner_name', models.CharField(max_length=32, unique=True)),
                ('primary_role', models.CharField(choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], max_length=20)),
                ('secondary_role', models.CharField(choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], max_length=20)),
                ('games_played', models.PositiveIntegerField(default=0)),
                ('mins_played', models.PositiveIntegerField(default=0)),
                ('first_bloods', models.PositiveIntegerField(default=0)),
                ('largest_multi_kill', models.PositiveIntegerField(default=0)),
                ('first_tower', models.PositiveIntegerField(default=0)),
                ('kills', models.PositiveIntegerField(default=0)),
                ('deaths', models.PositiveIntegerField(default=0)),
                ('assists', models.PositiveIntegerField(default=0)),
                ('creep_score', models.PositiveIntegerField(default=0)),
                ('gold', models.PositiveIntegerField(default=0)),
                ('gold_share', models.FloatField(default=0)),
                ('damage_done', models.PositiveIntegerField(default=0)),
                ('damage_share', models.FloatField(default=0)),
                ('vision_score', models.PositiveIntegerField(default=0)),
                ('crowd_control_score', models.PositiveIntegerField(default=0)),
                ('csd_at_ten', models.FloatField(default=0)),
                ('KDA', models.FloatField(default=0)),
                ('avg_kills', models.FloatField(default=0)),
                ('avg_deaths', models.FloatField(default=0)),
                ('avg_assists', models.FloatField(default=0)),
                ('avg_creep_score', models.FloatField(default=0)),
                ('avg_gold', models.FloatField(default=0)),
                ('avg_gold_share', models.FloatField(default=0)),
                ('avg_damage_done', models.FloatField(default=0)),
                ('avg_damage_share', models.FloatField(default=0)),
                ('avg_vision_score', models.FloatField(default=0)),
                ('avg_crowd_control_score', models.FloatField(default=0)),
                ('avg_csd_at_ten', models.FloatField(default=0)),
                ('creep_score_per_minute', models.FloatField(default=0)),
                ('gold_per_minute', models.FloatField(default=0)),
                ('damage_done_per_minute', models.FloatField(default=0)),
                ('vision_score_per_minute', models.FloatField(default=0)),
                ('crowd_control_score_per_minute', models.FloatField(default=0)),
            ],
            options={
                'verbose_name_plural': 'Baron Players',
                'db_table': 'Baron Players',
            },
        ),
        migrations.CreateModel(
            name='Baron_Post',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=64)),
                ('date', models.DateTimeField()),
                ('author', models.CharField(max_length=64)),
                ('body', models.TextField()),
            ],
            options={
                'verbose_name_plural': 'Baron News',
                'db_table': 'Baron News',
            },
        ),
        migrations.CreateModel(
            name='Baron_Team_Sign_Ups',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('acronym', models.CharField(max_length=4)),
                ('team_name', models.CharField(max_length=25)),
                ('wins', models.PositiveIntegerField(default=0)),
                ('losses', models.PositiveIntegerField(default=0)),
                ('tie_breaker', models.PositiveIntegerField(default=0)),
                ('is_active', models.BooleanField(default=True, help_text='This will change to false whenever the League is over.')),
                ('top_laner', models.CharField(max_length=32)),
                ('jungler', models.CharField(max_length=32)),
                ('mid_laner', models.CharField(max_length=32)),
                ('ad_carry', models.CharField(max_length=32)),
                ('support', models.CharField(max_length=32)),
                ('substitute1', models.CharField(blank=True, max_length=32)),
                ('sub1_role', models.CharField(blank=True, choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], default='N/A', max_length=20)),
                ('substitute2', models.CharField(blank=True, max_length=32)),
                ('sub2_role', models.CharField(blank=True, choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], default='N/A', max_length=20)),
                ('substitute3', models.CharField(blank=True, max_length=32)),
                ('sub3_role', models.CharField(blank=True, choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], default='N/A', max_length=20)),
                ('coach', models.CharField(blank=True, max_length=32)),
                ('your_summoner_name', models.CharField(max_length=28)),
                ('discord_name', models.CharField(max_length=30)),
                ('email_address', models.EmailField(max_length=100)),
                ('time_created', models.DateTimeField(auto_now_add=True)),
            ],
            options={
                'verbose_name_plural': 'Baron Sign Ups',
                'db_table': 'Baron League Sign Up',
            },
        ),
        migrations.CreateModel(
            name='Dragon_League_Rosters',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('acronym', models.CharField(max_length=4)),
                ('team_name', models.CharField(max_length=25)),
                ('wins', models.PositiveIntegerField(default=0)),
                ('losses', models.PositiveIntegerField(default=0)),
                ('tie_breaker', models.PositiveIntegerField(default=0)),
                ('is_active', models.BooleanField(default=True, help_text='This will change to false whenever the League is over.')),
                ('sub1_role', models.CharField(blank=True, choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], default='N/A', max_length=20)),
                ('sub2_role', models.CharField(blank=True, choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], default='N/A', max_length=20)),
                ('sub3_role', models.CharField(blank=True, choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], default='N/A', max_length=20)),
                ('coach', models.CharField(blank=True, max_length=32)),
            ],
            options={
                'verbose_name_plural': 'Dragon Rosters',
                'db_table': 'Dragon Rosters',
            },
        ),
        migrations.CreateModel(
            name='Dragon_Players',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('summoner_name', models.CharField(max_length=32, unique=True)),
                ('primary_role', models.CharField(choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], max_length=20)),
                ('secondary_role', models.CharField(choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], max_length=20)),
                ('games_played', models.PositiveIntegerField(default=0)),
                ('mins_played', models.PositiveIntegerField(default=0)),
                ('first_bloods', models.PositiveIntegerField(default=0)),
                ('largest_multi_kill', models.PositiveIntegerField(default=0)),
                ('first_tower', models.PositiveIntegerField(default=0)),
                ('kills', models.PositiveIntegerField(default=0)),
                ('deaths', models.PositiveIntegerField(default=0)),
                ('assists', models.PositiveIntegerField(default=0)),
                ('creep_score', models.PositiveIntegerField(default=0)),
                ('gold', models.PositiveIntegerField(default=0)),
                ('gold_share', models.FloatField(default=0)),
                ('damage_done', models.PositiveIntegerField(default=0)),
                ('damage_share', models.FloatField(default=0)),
                ('vision_score', models.PositiveIntegerField(default=0)),
                ('crowd_control_score', models.PositiveIntegerField(default=0)),
                ('csd_at_ten', models.FloatField(default=0)),
                ('KDA', models.FloatField(default=0)),
                ('avg_kills', models.FloatField(default=0)),
                ('avg_deaths', models.FloatField(default=0)),
                ('avg_assists', models.FloatField(default=0)),
                ('avg_creep_score', models.FloatField(default=0)),
                ('avg_gold', models.FloatField(default=0)),
                ('avg_gold_share', models.FloatField(default=0)),
                ('avg_damage_done', models.FloatField(default=0)),
                ('avg_damage_share', models.FloatField(default=0)),
                ('avg_vision_score', models.FloatField(default=0)),
                ('avg_crowd_control_score', models.FloatField(default=0)),
                ('avg_csd_at_ten', models.FloatField(default=0)),
                ('creep_score_per_minute', models.FloatField(default=0)),
                ('gold_per_minute', models.FloatField(default=0)),
                ('damage_done_per_minute', models.FloatField(default=0)),
                ('vision_score_per_minute', models.FloatField(default=0)),
                ('crowd_control_score_per_minute', models.FloatField(default=0)),
            ],
            options={
                'verbose_name_plural': 'Dragon Players',
                'db_table': 'Dragon Players',
            },
        ),
        migrations.CreateModel(
            name='Dragon_Post',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=64)),
                ('date', models.DateTimeField()),
                ('author', models.CharField(max_length=64)),
                ('body', models.TextField()),
            ],
            options={
                'verbose_name_plural': 'Dragon News',
                'db_table': 'Dragon News',
            },
        ),
        migrations.CreateModel(
            name='Dragon_Solo_Sign_Ups',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('your_summoner_name', models.CharField(max_length=28)),
                ('primary_role', models.CharField(choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], max_length=20)),
                ('secondary_role', models.CharField(choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], max_length=20)),
                ('discord_name', models.CharField(max_length=30)),
                ('email_address', models.EmailField(max_length=100)),
                ('time_created', models.DateTimeField(auto_now_add=True)),
            ],
            options={
                'verbose_name_plural': 'Dragon Solo Sign Ups',
                'db_table': 'Dragon Solo Sign Up',
            },
        ),
        migrations.CreateModel(
            name='Elder_League_Rosters',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('acronym', models.CharField(max_length=4)),
                ('team_name', models.CharField(max_length=25)),
                ('wins', models.PositiveIntegerField(default=0)),
                ('losses', models.PositiveIntegerField(default=0)),
                ('tie_breaker', models.PositiveIntegerField(default=0)),
                ('is_active', models.BooleanField(default=True, help_text='This will change to false whenever the League is over.')),
                ('sub1_role', models.CharField(blank=True, choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], default='N/A', max_length=20)),
                ('sub2_role', models.CharField(blank=True, choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], default='N/A', max_length=20)),
                ('sub3_role', models.CharField(blank=True, choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], default='N/A', max_length=20)),
                ('coach', models.CharField(blank=True, max_length=32)),
            ],
            options={
                'verbose_name_plural': 'Elder Rosters',
                'db_table': 'Elder Rosters',
            },
        ),
        migrations.CreateModel(
            name='Elder_Players',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('summoner_name', models.CharField(max_length=32, unique=True)),
                ('primary_role', models.CharField(choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], max_length=20)),
                ('secondary_role', models.CharField(choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], max_length=20)),
                ('games_played', models.PositiveIntegerField(default=0)),
                ('mins_played', models.PositiveIntegerField(default=0)),
                ('first_bloods', models.PositiveIntegerField(default=0)),
                ('largest_multi_kill', models.PositiveIntegerField(default=0)),
                ('first_tower', models.PositiveIntegerField(default=0)),
                ('kills', models.PositiveIntegerField(default=0)),
                ('deaths', models.PositiveIntegerField(default=0)),
                ('assists', models.PositiveIntegerField(default=0)),
                ('creep_score', models.PositiveIntegerField(default=0)),
                ('gold', models.PositiveIntegerField(default=0)),
                ('gold_share', models.FloatField(default=0)),
                ('damage_done', models.PositiveIntegerField(default=0)),
                ('damage_share', models.FloatField(default=0)),
                ('vision_score', models.PositiveIntegerField(default=0)),
                ('crowd_control_score', models.PositiveIntegerField(default=0)),
                ('csd_at_ten', models.FloatField(default=0)),
                ('KDA', models.FloatField(default=0)),
                ('avg_kills', models.FloatField(default=0)),
                ('avg_deaths', models.FloatField(default=0)),
                ('avg_assists', models.FloatField(default=0)),
                ('avg_creep_score', models.FloatField(default=0)),
                ('avg_gold', models.FloatField(default=0)),
                ('avg_gold_share', models.FloatField(default=0)),
                ('avg_damage_done', models.FloatField(default=0)),
                ('avg_damage_share', models.FloatField(default=0)),
                ('avg_vision_score', models.FloatField(default=0)),
                ('avg_crowd_control_score', models.FloatField(default=0)),
                ('avg_csd_at_ten', models.FloatField(default=0)),
                ('creep_score_per_minute', models.FloatField(default=0)),
                ('gold_per_minute', models.FloatField(default=0)),
                ('damage_done_per_minute', models.FloatField(default=0)),
                ('vision_score_per_minute', models.FloatField(default=0)),
                ('crowd_control_score_per_minute', models.FloatField(default=0)),
            ],
            options={
                'verbose_name_plural': 'Elder Players',
                'db_table': 'Elder Players',
            },
        ),
        migrations.CreateModel(
            name='Elder_Post',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=64)),
                ('date', models.DateTimeField()),
                ('author', models.CharField(max_length=64)),
                ('body', models.TextField()),
            ],
            options={
                'verbose_name_plural': 'Elder News',
                'db_table': 'Elder News',
            },
        ),
        migrations.CreateModel(
            name='Elder_Solo_Sign_Ups',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('your_summoner_name', models.CharField(max_length=28)),
                ('primary_role', models.CharField(choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], max_length=20)),
                ('secondary_role', models.CharField(choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], max_length=20)),
                ('discord_name', models.CharField(max_length=30)),
                ('email_address', models.EmailField(max_length=100)),
                ('time_created', models.DateTimeField(auto_now_add=True)),
                ('duo_partner', models.CharField(blank=True, max_length=20)),
            ],
            options={
                'verbose_name_plural': 'Elder Solo Sign Ups',
                'db_table': 'Elder Solo Sign Up',
            },
        ),
        migrations.CreateModel(
            name='Elder_Team_Sign_Ups',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('acronym', models.CharField(max_length=4)),
                ('team_name', models.CharField(max_length=25)),
                ('wins', models.PositiveIntegerField(default=0)),
                ('losses', models.PositiveIntegerField(default=0)),
                ('tie_breaker', models.PositiveIntegerField(default=0)),
                ('is_active', models.BooleanField(default=True, help_text='This will change to false whenever the League is over.')),
                ('top_laner', models.CharField(max_length=32)),
                ('jungler', models.CharField(max_length=32)),
                ('mid_laner', models.CharField(max_length=32)),
                ('ad_carry', models.CharField(max_length=32)),
                ('support', models.CharField(max_length=32)),
                ('substitute1', models.CharField(blank=True, max_length=32)),
                ('sub1_role', models.CharField(blank=True, choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], default='N/A', max_length=20)),
                ('substitute2', models.CharField(blank=True, max_length=32)),
                ('sub2_role', models.CharField(blank=True, choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], default='N/A', max_length=20)),
                ('substitute3', models.CharField(blank=True, max_length=32)),
                ('sub3_role', models.CharField(blank=True, choices=[('Top', 'Top'), ('Jungle', 'Jungle'), ('Mid', 'Mid'), ('ADC', 'ADC'), ('Support', 'Support'), ('Fill', 'Fill')], default='N/A', max_length=20)),
                ('coach', models.CharField(blank=True, max_length=32)),
                ('your_summoner_name', models.CharField(max_length=28)),
                ('discord_name', models.CharField(max_length=30)),
                ('email_address', models.EmailField(max_length=100)),
                ('time_created', models.DateTimeField(auto_now_add=True)),
            ],
            options={
                'verbose_name_plural': 'Elder Team Sign Ups',
                'db_table': 'Elder Team Sign Up',
            },
        ),
        migrations.CreateModel(
            name='Start_League',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('league_name', models.CharField(default='Dragon League X', max_length=50)),
                ('league', models.CharField(choices=[('Dragon', 'Dragon'), ('Elder', 'Elder'), ('Baron', 'Baron')], max_length=50)),
                ('start_date', models.DateTimeField()),
                ('week_length', models.PositiveIntegerField(choices=[(5, 5), (9, 9)], default=9)),
                ('regular_season_schedule', models.PositiveIntegerField(choices=[(1, 'Bo1'), (2, 'Bo2'), (3, 'Bo3')], default=1)),
                ('number_of_teams', models.PositiveIntegerField(default=10, help_text='This is always assumed to be 10')),
                ('pools', models.PositiveIntegerField(default=1, help_text='In case we got multiple Elder Leagues again')),
            ],
            options={
                'verbose_name_plural': 'Start League',
                'db_table': 'Start League',
            },
        ),
        migrations.AddField(
            model_name='elder_league_rosters',
            name='ad_carry',
            field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='ad_carry', to='AscensionESports_Baseline.Elder_Players'),
        ),
        migrations.AddField(
            model_name='elder_league_rosters',
            name='jungler',
            field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='jungler', to='AscensionESports_Baseline.Elder_Players'),
        ),
        migrations.AddField(
            model_name='elder_league_rosters',
            name='mid_laner',
            field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='mid_laner', to='AscensionESports_Baseline.Elder_Players'),
        ),
        migrations.AddField(
            model_name='elder_league_rosters',
            name='substitute1',
            field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='substitute1', to='AscensionESports_Baseline.Elder_Players'),
        ),
        migrations.AddField(
            model_name='elder_league_rosters',
            name='substitute2',
            field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='substitute2', to='AscensionESports_Baseline.Elder_Players'),
        ),
        migrations.AddField(
            model_name='elder_league_rosters',
            name='substitute3',
            field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='substitute3', to='AscensionESports_Baseline.Elder_Players'),
        ),
        migrations.AddField(
            model_name='elder_league_rosters',
            name='support',
            field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='support', to='AscensionESports_Baseline.Elder_Players'),
        ),
        migrations.AddField(
            model_name='elder_league_rosters',
            name='top_laner',
            field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='top_laner', to='AscensionESports_Baseline.Elder_Players'),
        ),
        migrations.AddField(
            model_name='dragon_league_rosters',
            name='ad_carry',
            field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='ad_carry', to='AscensionESports_Baseline.Dragon_Players'),
        ),
        migrations.AddField(
            model_name='dragon_league_rosters',
            name='jungler',
            field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='jungler', to='AscensionESports_Baseline.Dragon_Players'),
        ),
        migrations.AddField(
            model_name='dragon_league_rosters',
            name='mid_laner',
            field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='mid_laner', to='AscensionESports_Baseline.Dragon_Players'),
        ),
        migrations.AddField(
            model_name='dragon_league_rosters',
            name='substitute1',
            field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='substitute1', to='AscensionESports_Baseline.Dragon_Players'),
        ),
        migrations.AddField(
            model_name='dragon_league_rosters',
            name='substitute2',
            field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='substitute2', to='AscensionESports_Baseline.Dragon_Players'),
        ),
        migrations.AddField(
            model_name='dragon_league_rosters',
            name='substitute3',
            field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='substitute3', to='AscensionESports_Baseline.Dragon_Players'),
        ),
        migrations.AddField(
            model_name='dragon_league_rosters',
            name='support',
            field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='support', to='AscensionESports_Baseline.Dragon_Players'),
        ),
        migrations.AddField(
            model_name='dragon_league_rosters',
            name='top_laner',
            field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='top_laner', to='AscensionESports_Baseline.Dragon_Players'),
        ),
        migrations.AddField(
            model_name='baron_match_report',
            name='blue_ad_carry',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='blue_ad_carry', to='AscensionESports_Baseline.Baron_Players'),
        ),
        migrations.AddField(
            model_name='baron_match_report',
            name='blue_jungler',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='blue_jungler', to='AscensionESports_Baseline.Baron_Players'),
        ),
        migrations.AddField(
            model_name='baron_match_report',
            name='blue_mid_laner',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='blue_mid_laner', to='AscensionESports_Baseline.Baron_Players'),
        ),
        migrations.AddField(
            model_name='baron_match_report',
            name='blue_support',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='blue_support', to='AscensionESports_Baseline.Baron_Players'),
        ),
        migrations.AddField(
            model_name='baron_match_report',
            name='blue_team',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='blue_team', to='AscensionESports_Baseline.Baron_League_Rosters'),
        ),
        migrations.AddField(
            model_name='baron_match_report',
            name='blue_top_laner',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='blue_top_laner', to='AscensionESports_Baseline.Baron_Players'),
        ),
        migrations.AddField(
            model_name='baron_match_report',
            name='red_ad_carry',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='red_ad_carry', to='AscensionESports_Baseline.Baron_Players'),
        ),
        migrations.AddField(
            model_name='baron_match_report',
            name='red_jungler',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='red_jungler', to='AscensionESports_Baseline.Baron_Players'),
        ),
        migrations.AddField(
            model_name='baron_match_report',
            name='red_mid_laner',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='red_mid_laner', to='AscensionESports_Baseline.Baron_Players'),
        ),
        migrations.AddField(
            model_name='baron_match_report',
            name='red_support',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='red_support', to='AscensionESports_Baseline.Baron_Players'),
        ),
        migrations.AddField(
            model_name='baron_match_report',
            name='red_team',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='red_team', to='AscensionESports_Baseline.Baron_League_Rosters'),
        ),
        migrations.AddField(
            model_name='baron_match_report',
            name='red_top_laner',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='red_top_laner', to='AscensionESports_Baseline.Baron_Players'),
        ),
        migrations.AddField(
            model_name='baron_league_rosters',
            name='ad_carry',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ad_carry', to='AscensionESports_Baseline.Baron_Players'),
        ),
        migrations.AddField(
            model_name='baron_league_rosters',
            name='jungler',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='jungler', to='AscensionESports_Baseline.Baron_Players'),
        ),
        migrations.AddField(
            model_name='baron_league_rosters',
            name='mid_laner',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='mid_laner', to='AscensionESports_Baseline.Baron_Players'),
        ),
        migrations.AddField(
            model_name='baron_league_rosters',
            name='substitute1',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='substitute1', to='AscensionESports_Baseline.Baron_Players'),
        ),
        migrations.AddField(
            model_name='baron_league_rosters',
            name='substitute2',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='substitute2', to='AscensionESports_Baseline.Baron_Players'),
        ),
        migrations.AddField(
            model_name='baron_league_rosters',
            name='substitute3',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='substitute3', to='AscensionESports_Baseline.Baron_Players'),
        ),
        migrations.AddField(
            model_name='baron_league_rosters',
            name='support',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='support', to='AscensionESports_Baseline.Baron_Players'),
        ),
        migrations.AddField(
            model_name='baron_league_rosters',
            name='top_laner',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='top_laner', to='AscensionESports_Baseline.Baron_Players'),
        ),
        migrations.AlterUniqueTogether(
            name='baron_match_report',
            unique_together=set([('blue_team', 'red_team', 'match_time')]),
        ),
    ]
Ejemplo n.º 18
0
class Collect(models.Model):
    """用户收藏帖子表"""
    user = models.ForeignKey(UserInfo, on_delete=models.CASCADE)
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    status = models.BooleanField(default=True)
Ejemplo n.º 19
0
class Migration(migrations.Migration):

    dependencies = [
        ("contenttypes", "0001_initial"),
    ]

    operations = [
        migrations.CreateModel(
            name='User',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  verbose_name='ID',
                                  serialize=False,
                                  primary_key=True)),
                ('password',
                 models.CharField(max_length=128, verbose_name='password')),
                ('last_login',
                 models.DateTimeField(default=django.utils.timezone.now,
                                      verbose_name='last login')),
                ('is_superuser',
                 models.BooleanField(
                     default=False,
                     help_text=
                     'Designates that this user has all permissions without explicitly assigning them.',
                     verbose_name='superuser status')),
                ('username',
                 models.CharField(
                     max_length=30,
                     help_text=
                     'Required. 30 characters or fewer. Letters, numbers and /./-/_ characters',
                     verbose_name='username',
                     unique=True,
                     validators=[
                         django.core.validators.RegexValidator(
                             re.compile('^[\\w.-]+$', 32),
                             'Enter a valid username.', 'invalid')
                     ])),
                ('email',
                 models.EmailField(max_length=75,
                                   blank=True,
                                   verbose_name='email address')),
                ('is_active',
                 models.BooleanField(
                     default=True,
                     help_text=
                     'Designates whether this user should be treated as active. Unselect this instead of deleting accounts.',
                     verbose_name='active')),
                ('full_name',
                 models.CharField(max_length=256,
                                  blank=True,
                                  verbose_name='full name')),
                ('color',
                 models.CharField(
                     default=tuesmon.users.models.generate_random_hex_color,
                     max_length=9,
                     blank=True,
                     verbose_name='color')),
                ('bio',
                 models.TextField(default='',
                                  blank=True,
                                  verbose_name='biography')),
                ('photo',
                 models.FileField(null=True,
                                  max_length=500,
                                  blank=True,
                                  verbose_name='photo',
                                  upload_to='users/photo')),
                ('date_joined',
                 models.DateTimeField(default=django.utils.timezone.now,
                                      verbose_name='date joined')),
                ('default_language',
                 models.CharField(default='',
                                  max_length=20,
                                  blank=True,
                                  verbose_name='default language')),
                ('default_timezone',
                 models.CharField(default='',
                                  max_length=20,
                                  blank=True,
                                  verbose_name='default timezone')),
                ('colorize_tags',
                 models.BooleanField(default=False,
                                     verbose_name='colorize tags')),
                ('token',
                 models.CharField(default=None,
                                  max_length=200,
                                  blank=True,
                                  verbose_name='token',
                                  null=True)),
                ('email_token',
                 models.CharField(default=None,
                                  max_length=200,
                                  blank=True,
                                  verbose_name='email token',
                                  null=True)),
                ('new_email',
                 models.EmailField(null=True,
                                   max_length=75,
                                   blank=True,
                                   verbose_name='new email address')),
                ('github_id',
                 models.IntegerField(null=True,
                                     blank=True,
                                     verbose_name='github ID')),
            ],
            options={
                'verbose_name_plural': 'users',
                'permissions': (('view_user', 'Can view user'), ),
                'verbose_name': 'user',
                'ordering': ['username'],
            },
            bases=(models.Model, ),
        ),
    ]
Ejemplo n.º 20
0
class ForumPower(models.Model):
    """版块权限表"""
    user = models.ForeignKey(UserInfo, on_delete=models.CASCADE)
    forum = models.ForeignKey(Forum, null=True, on_delete=models.CASCADE)
    status = models.BooleanField(default=True)
Ejemplo n.º 21
0
class AbstractRange(models.Model):
    """
    Represents a range of products that can be used within an offer.

    Ranges only support adding parent or stand-alone products. Offers will
    consider child products automatically.
    """
    name = models.CharField(_("Name"), max_length=128, unique=True)
    slug = fields.AutoSlugField(
        _("Slug"), max_length=128, unique=True, populate_from="name")

    description = models.TextField(blank=True)

    # Whether this range is public
    is_public = models.BooleanField(
        _('Is public?'), default=False,
        help_text=_("Public ranges have a customer-facing page"))

    includes_all_products = models.BooleanField(
        _('Includes all products?'), default=False)

    included_products = models.ManyToManyField(
        'catalogue.Product', related_name='includes', blank=True,
        verbose_name=_("Included Products"), through='offer.RangeProduct')
    excluded_products = models.ManyToManyField(
        'catalogue.Product', related_name='excludes', blank=True,
        verbose_name=_("Excluded Products"))
    classes = models.ManyToManyField(
        'catalogue.ProductClass', related_name='classes', blank=True,
        verbose_name=_("Product Types"))
    included_categories = models.ManyToManyField(
        'catalogue.Category', related_name='includes', blank=True,
        verbose_name=_("Included Categories"))

    # Allow a custom range instance to be specified
    proxy_class = fields.NullCharField(
        _("Custom class"), max_length=255, default=None, unique=True)

    date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)

    __included_product_ids = None
    __excluded_product_ids = None
    __included_categories = None
    __class_ids = None
    __category_ids = None

    objects = models.Manager()
    browsable = BrowsableRangeManager()

    class Meta:
        abstract = True
        app_label = 'offer'
        verbose_name = _("Range")
        verbose_name_plural = _("Ranges")

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse(
            'catalogue:range', kwargs={'slug': self.slug})

    @cached_property
    def proxy(self):
        if self.proxy_class:
            return load_proxy(self.proxy_class)()

    def add_product(self, product, display_order=None):
        """ Add product to the range

        When adding product that is already in the range, prevent re-adding it.
        If display_order is specified, update it.

        Default display_order for a new product in the range is 0; this puts
        the product at the top of the list.
        """

        initial_order = display_order or 0
        RangeProduct = get_model('offer', 'RangeProduct')
        relation, __ = RangeProduct.objects.get_or_create(
            range=self, product=product,
            defaults={'display_order': initial_order})

        if (display_order is not None and
                relation.display_order != display_order):
            relation.display_order = display_order
            relation.save()

        # Remove product from excluded products if it was removed earlier and
        # re-added again, thus it returns back to the range product list.
        if product.id in self._excluded_product_ids():
            self.excluded_products.remove(product)
            self.invalidate_cached_ids()

    def remove_product(self, product):
        """
        Remove product from range. To save on queries, this function does not
        check if the product is in fact in the range.
        """
        RangeProduct = get_model('offer', 'RangeProduct')
        RangeProduct.objects.filter(range=self, product=product).delete()
        # Making sure product will be excluded from range products list by adding to
        # respective field. Otherwise, it could be included as a product from included
        # category or etc.
        self.excluded_products.add(product)
        # Invalidating cached property value with list of IDs of already excluded products.
        self.invalidate_cached_ids()

    def contains_product(self, product):  # noqa (too complex (12))
        """
        Check whether the passed product is part of this range.
        """

        # Delegate to a proxy class if one is provided
        if self.proxy:
            return self.proxy.contains_product(product)

        excluded_product_ids = self._excluded_product_ids()
        if product.id in excluded_product_ids:
            return False
        if self.includes_all_products:
            return True
        class_ids = self._class_ids()
        if class_ids and product.get_product_class().id in class_ids:
            return True
        included_product_ids = self._included_product_ids()
        # If the product's parent is in the range, the child is automatically included as well
        if product.is_child and product.parent.id in included_product_ids:
            return True
        if product.id in included_product_ids:
            return True
        test_categories = self._included_categories()
        if test_categories:
            for category in product.get_categories().only(
                    *self._category_comparison_fields):
                for test_category in test_categories:
                    if category == test_category \
                            or category.is_descendant_of(test_category):
                        return True
        return False

    # Deprecated alias
    @deprecated
    def contains(self, product):
        return self.contains_product(product)

    def __get_pks_and_child_pks(self, queryset):
        """
        Expects a product queryset; gets the primary keys of the passed
        products and their children.

        Verbose, but database and memory friendly.
        """
        # One query to get parent and children; [(4, None), (5, 10), (5, 11)]
        pk_tuples_iterable = queryset.values_list('pk', 'children__pk')
        # Flatten list without unpacking; [4, None, 5, 10, 5, 11]
        flat_iterable = itertools.chain.from_iterable(pk_tuples_iterable)
        # Ensure uniqueness and remove None; {4, 5, 10, 11}
        return set(flat_iterable) - {None}

    @cached_property
    def _category_comparison_fields(self):
        # Overwritten Category models could contain a lot of data, e.g CMS
        # content. Hence, this avoids fetching unneeded data in the costly
        # range comparison queries. Note that using .only() with an empty list
        # is a no-op essentially, so nothing breaks when the field is missing.
        Category = get_model('catalogue', 'Category')
        return getattr(Category, 'COMPARISON_FIELDS', ())

    def _included_categories(self):
        if not self.id:
            return self.included_categories.none()
        if self.__included_categories is None:
            self.__included_categories = self.included_categories.only(
                *self._category_comparison_fields)
        return self.__included_categories

    def _included_product_ids(self):
        if not self.id:
            return []
        if self.__included_product_ids is None:
            self.__included_product_ids = self.__get_pks_and_child_pks(
                self.included_products)
        return self.__included_product_ids

    def _excluded_product_ids(self):
        if not self.id:
            return []
        if self.__excluded_product_ids is None:
            self.__excluded_product_ids = self.__get_pks_and_child_pks(
                self.excluded_products)
        return self.__excluded_product_ids

    def _class_ids(self):
        if self.__class_ids is None:
            self.__class_ids = self.classes.values_list('pk', flat=True)
        return self.__class_ids

    def _category_ids(self):
        if self.__category_ids is None:
            ids = []
            for category in self._included_categories():
                children_ids = category.get_descendants().values_list(
                    'pk', flat=True)
                ids.append(category.pk)
                ids.extend(list(children_ids))

            self.__category_ids = ids

        return self.__category_ids

    def invalidate_cached_ids(self):
        self.__category_ids = None
        self.__included_categories = None
        self.__included_product_ids = None
        self.__excluded_product_ids = None

    def num_products(self):
        # Delegate to a proxy class if one is provided
        if self.proxy:
            return self.proxy.num_products()
        if self.includes_all_products:
            return None
        return self.all_products().count()

    def all_products(self):
        """
        Return a queryset containing all the products in the range

        This includes included_products plus the products contained in the
        included classes and categories, minus the products in
        excluded_products.
        """
        if self.proxy:
            return self.proxy.all_products()

        Product = get_model("catalogue", "Product")
        if self.includes_all_products:
            # Filter out child products and blacklisted products
            return Product.objects.browsable().exclude(
                id__in=self._excluded_product_ids())

        return Product.objects.filter(
            Q(id__in=self._included_product_ids()) |
            Q(product_class_id__in=self._class_ids()) |
            Q(productcategory__category_id__in=self._category_ids())
        ).exclude(id__in=self._excluded_product_ids()).distinct()

    @property
    def is_editable(self):
        """
        Test whether this range can be edited in the dashboard.
        """
        return not self.proxy_class

    @property
    def is_reorderable(self):
        """
        Test whether products for the range can be re-ordered.
        """
        return len(self._class_ids()) == 0 and len(self._included_categories()) == 0
Ejemplo n.º 22
0
class FloorGreat(models.Model):
    """楼层点赞表"""
    user = models.ForeignKey(UserInfo, on_delete=models.CASCADE)
    floor = models.ForeignKey(Floor, on_delete=models.CASCADE)
    status = models.BooleanField(default=True)
class Migration(migrations.Migration):

    dependencies = [
        ('articles', '0001_initial'),
        ('containers', '0002_auto_20170320_1223'),
        ('tags', '0002_auto_20170810_1608'),
    ]

    operations = [
        migrations.CreateModel(
            name='DataTagger',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('field_name',
                 models.CharField(
                     max_length=255,
                     help_text=
                     'The name of the Container field that should be analyzed for tagging. Use dot notation to indicate nested fields (e.g., "user.name").'
                 )),
                ('exact_match',
                 models.BooleanField(
                     default=False,
                     help_text=
                     'Match the entire content of the field. If checked, please select one and only one tag topic for analyzing this field.'
                 )),
                ('create_tags',
                 models.BooleanField(
                     default=False,
                     help_text=
                     'Create new tags from this field (only available when using exact match).'
                 )),
                ('container',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='containers.Container')),
                ('enabled', models.BooleanField(default=True)),
            ],
            options={
                'ordering': ['container', 'field_name'],
            },
        ),
        migrations.CreateModel(
            name='Topic',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('name', models.CharField(max_length=255, unique=True)),
            ],
            options={
                'ordering': ['name'],
            },
        ),
        migrations.AlterField(
            model_name='tag',
            name='name',
            field=models.CharField(
                help_text='Tags must be lowercase.',
                max_length=255,
                validators=[utils.validators.validators.lowercase_validator]),
        ),
        migrations.AddField(
            model_name='datatagger',
            name='topics',
            field=models.ManyToManyField(
                help_text=
                'Restrict tagging to these topics. If none are selected, all topics will be included in the analysis.',
                to='tags.Topic'),
        ),
        migrations.AddField(
            model_name='tag',
            name='article',
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name='tags',
                related_query_name='tag',
                to='articles.Article'),
        ),
        migrations.AddField(
            model_name='tag',
            name='topic',
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name='tags',
                related_query_name='tag',
                to='tags.Topic'),
        ),
        migrations.AlterModelOptions(
            name='tag',
            options={'ordering': ['topic', 'name']},
        ),
        migrations.AlterUniqueTogether(
            name='tag',
            unique_together=set([('name', 'topic')]),
        ),
        migrations.AlterUniqueTogether(
            name='datatagger',
            unique_together=set([('container', 'field_name')]),
        ),
    ]
Ejemplo n.º 24
0
class CommentGreat(models.Model):
    """回复点赞表"""
    user = models.ForeignKey(UserInfo, on_delete=models.CASCADE)
    comment = models.ForeignKey(Comment, on_delete=models.CASCADE)
    status = models.BooleanField(default=True)
Ejemplo n.º 25
0
class Strategy(Basemodel):
    is_manual_review = models.BooleanField(default=False, verbose_name='有流程')
Ejemplo n.º 26
0
class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Vuelos',
            fields=[
                ('id', models.AutoField(primary_key=True, serialize=False)),
                ('aerolinea', models.CharField(max_length=200)),
                ('costo', models.IntegerField()),
                ('NoCupos', models.IntegerField()),
                ('fechaSalida', models.DateField(max_length=200)),
                ('fechaLlegada', models.DateField(max_length=200)),
                ('horaSalida', models.TimeField(max_length=200)),
                ('horaLlegada', models.TimeField(max_length=200)),
                ('LugarSalida', models.CharField(max_length=200)),
                ('Destino', models.CharField(max_length=200)),
                ('estado',
                 models.BooleanField(default=True, verbose_name='Estado')),
            ],
            options={
                'verbose_name': 'Vuelo',
                'verbose_name_plural': 'Vuelos',
                'ordering': ['aerolinea'],
            },
        ),
        migrations.CreateModel(
            name='Reserva',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('fechaHoraReserva',
                 models.DateTimeField(default=django.utils.timezone.now)),
                ('idVuelo',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='Tuluayork.vuelos')),
                ('user',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'verbose_name': 'Reserva',
                'verbose_name_plural': 'Reservas',
            },
        ),
        migrations.CreateModel(
            name='Person',
            fields=[
                ('cedula',
                 models.IntegerField(primary_key=True, serialize=False)),
                ('nombre', models.CharField(max_length=100)),
                ('apellido', models.CharField(max_length=100)),
                ('edad', models.IntegerField()),
                ('fechaNacimiento', models.DateField(max_length=200)),
                ('ciudadResidencia', models.CharField(max_length=100)),
                ('tipoUsuario', models.IntegerField()),
                ('estado',
                 models.BooleanField(default=True, verbose_name='Estado')),
                ('user',
                 models.OneToOneField(
                     on_delete=django.db.models.deletion.CASCADE,
                     to=settings.AUTH_USER_MODEL)),
            ],
        ),
    ]
Ejemplo n.º 27
0
class Migration(migrations.Migration):

    initial = True

    dependencies = []

    operations = [
        migrations.CreateModel(
            name='Ad',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('title', models.CharField(max_length=255)),
                ('image_url', models.CharField(max_length=255)),
                ('link', models.CharField(blank=True,
                                          max_length=255,
                                          null=True)),
                ('is_approved', models.BooleanField(default=False)),
                ('create_time',
                 models.DateTimeField(default=django.utils.timezone.now)),
            ],
        ),
        migrations.CreateModel(
            name='View',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('time', models.DateTimeField(auto_now_add=True)),
                ('ip', models.GenericIPAddressField()),
                ('ad',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   related_name='views',
                                   to='advertising.ad')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Click',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('time', models.DateTimeField(auto_now_add=True)),
                ('ip', models.GenericIPAddressField()),
                ('view_delay', models.DurationField()),
                ('ad',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   related_name='clicks',
                                   to='advertising.ad')),
            ],
            options={
                'abstract': False,
            },
        ),
    ]
Ejemplo n.º 28
0
class Barrier(FullyArchivableMixin, BaseModel):
    """ Barrier Instance, converted from a completed and accepted Report """

    id = models.UUIDField(primary_key=True, default=uuid4)
    code = models.CharField(
        max_length=MAX_LENGTH,
        blank=True,
        null=True,
        unique=True,
        help_text="Readable reference code e.g. B-20-NTZ",
        db_index=True,
    )
    term = models.PositiveIntegerField(
        choices=BARRIER_TERMS,
        blank=True,
        null=True,
        help_text=
        "Is this a short-term procedural or long-term strategic barrier?",
    )
    end_date = models.DateField(blank=True,
                                null=True,
                                help_text="Date the barrier ends")
    country = models.UUIDField(blank=True, null=True)
    admin_areas = ArrayField(
        models.UUIDField(),
        blank=True,
        default=list,
        help_text="list of states, provinces, regions etc within a country",
    )
    trading_bloc = models.CharField(
        choices=TRADING_BLOC_CHOICES,
        max_length=7,
        blank=True,
    )
    caused_by_trading_bloc = models.BooleanField(null=True)
    trade_direction = models.SmallIntegerField(
        choices=TRADE_DIRECTION_CHOICES,
        blank=True,
        null=True,
    )
    sectors_affected = models.BooleanField(
        help_text="Does the barrier affect any sectors?",
        null=True,
        blank=True,
    )
    all_sectors = models.BooleanField(
        help_text="Does the barrier affect all sectors?",
        null=True,
        blank=True,
    )
    sectors = ArrayField(
        models.UUIDField(),
        blank=True,
        default=list,
    )
    companies = models.JSONField(blank=True, null=True)
    product = models.CharField(max_length=MAX_LENGTH, blank=True)
    source = models.CharField(choices=BARRIER_SOURCE,
                              max_length=25,
                              blank=True)
    other_source = models.CharField(max_length=MAX_LENGTH, blank=True)
    title = models.CharField(max_length=MAX_LENGTH, blank=True)
    summary = models.TextField(blank=True)
    is_summary_sensitive = models.BooleanField(
        help_text="Does the summary contain sensitive information?",
        blank=True,
        null=True,
    )
    # next steps will be saved here momentarily during reporting.
    # once the report is ready for submission, this will be added as a new note
    next_steps_summary = models.TextField(blank=True)
    categories = models.ManyToManyField(Category, related_name="barriers")
    reported_on = models.DateTimeField(db_index=True, auto_now_add=True)

    # Barrier status
    status = models.PositiveIntegerField(choices=BarrierStatus.choices,
                                         default=0)
    sub_status = models.CharField(
        choices=BARRIER_PENDING,
        max_length=25,
        blank=True,
    )
    sub_status_other = models.CharField(
        max_length=MAX_LENGTH,
        blank=True,
        help_text="Text if sub status is 'OTHER'",
    )
    status_summary = models.TextField(blank=True)
    status_date = models.DateField(
        blank=True,
        null=True,
        help_text=
        ("If resolved or part-resolved, the month and year supplied by the user, "
         "otherwise the current time when the status was set."))
    commercial_value = models.BigIntegerField(blank=True, null=True)
    commercial_value_explanation = models.TextField(blank=True)
    economic_assessment_eligibility = models.BooleanField(
        blank=True,
        null=True,
        help_text="Is the barrier eligible for an economic assessment?",
    )
    economic_assessment_eligibility_summary = models.TextField(
        blank=True,
        help_text=
        "Why is the barrier eligible/ineligible for an economic assessment?",
    )
    public_eligibility = models.BooleanField(
        blank=True,
        null=True,
        help_text=
        "Mark the barrier as either publishable or unpublishable to the public.",
    )
    public_eligibility_summary = models.TextField(
        blank=True,
        help_text="Public eligibility summary if provided by user.",
    )

    # Barrier priority
    priority = models.ForeignKey(
        BarrierPriority,
        default=1,
        related_name="barrier",
        on_delete=models.PROTECT,
    )
    priority_summary = models.TextField(blank=True)
    priority_date = models.DateTimeField(auto_now=True, blank=True, null=True)
    stages = models.ManyToManyField(
        Stage,
        related_name="report_stages",
        through="BarrierReportStage",
        help_text="Store reporting stages before submitting",
    )
    archived_reason = models.CharField(
        choices=BARRIER_ARCHIVED_REASON,
        max_length=25,
        blank=True,
    )
    archived_explanation = models.TextField(blank=True)
    commodities = models.ManyToManyField(Commodity, through="BarrierCommodity")
    trade_category = models.CharField(choices=TRADE_CATEGORIES,
                                      max_length=32,
                                      blank=True)
    draft = models.BooleanField(default=True)
    organisations = models.ManyToManyField(
        Organisation,
        help_text="Organisations that are related to the barrier")

    history = HistoricalRecords(bases=[BarrierHistoricalModel])

    tags = models.ManyToManyField(BarrierTag)

    def __str__(self):
        if self.title is None:
            return self.code
        return self.title

    objects = models.Manager()
    reports = ReportManager()
    barriers = BarrierManager()

    class Meta:
        ordering = ["-reported_on"]
        permissions = [
            ('change_barrier_public_eligibility',
             'Can change barrier public eligibility'),
        ]

    @property
    def country_name(self):
        if self.country:
            country = get_country(str(self.country))
            return country.get("name")

    @property
    def country_trading_bloc(self):
        if self.country:
            return get_trading_bloc_by_country_id(str(self.country))

    @property
    def location(self):
        return get_location_text(
            country_id=self.country,
            trading_bloc=self.trading_bloc,
            caused_by_trading_bloc=self.caused_by_trading_bloc,
            admin_area_ids=self.admin_areas,
        )

    def current_progress(self):
        """ checks current dataset to see how far reporting workflow is done """
        progress_list = []
        for stage in REPORT_CONDITIONS:
            stage_code, status = report_stage_status(self, stage)
            progress_list.append((Stage.objects.get(code=stage_code), status))

        return progress_list

    @property
    def current_economic_assessment(self):
        """
        Get the current economic assessment

        Filter in python to avoid another db call if prefetch_related has been used.
        """
        for assessment in self.economic_assessments.all():
            if assessment.approved and not assessment.archived:
                return assessment

    @property
    def current_resolvability_assessment(self):
        """
        Get the current resolvability assessment

        Filter in python to avoid another db call if prefetch_related has been used.
        """
        for assessment in self.resolvability_assessments.all():
            if assessment.approved and not assessment.archived:
                return assessment

    @property
    def current_strategic_assessment(self):
        """
        Get the current strategic assessment

        Filter in python to avoid another db call if prefetch_related has been used.
        """
        for assessment in self.strategic_assessments.all():
            if assessment.approved and not assessment.archived:
                return assessment

    @property
    def government_organisations(self):
        """ Only returns government organisations """
        return self.organisations.filter(
            organisation_type__in=GOVERNMENT_ORGANISATION_TYPES)

    @government_organisations.setter
    def government_organisations(self, queryset):
        """
        Replaces existing government organisations with the items in queryset,
        leaves non government organisations intact.
        """
        non_gov_orgs_qs = self.organisations.exclude(
            organisation_type__in=GOVERNMENT_ORGANISATION_TYPES)
        self.organisations.set(non_gov_orgs_qs | queryset)

    def submit_report(self, submitted_by=None):
        """ submit a report, convert it into a barrier """
        for validator in [validators.ReportReadyForSubmitValidator()]:
            validator.set_instance(self)
            validator()

        if not self.status_date:
            self.status_date = timezone.now()

        self.modified_by = submitted_by
        self.reported_on = timezone.now()
        self.draft = False
        self.save()
        self.progress.all().delete()
        return self

    @property
    def archived_user(self):
        return self._cleansed_username(self.archived_by)

    @property
    def unarchived_user(self):
        return self._cleansed_username(self.unarchived_by)

    @property
    def created_user(self):
        return self._cleansed_username(self.created_by)

    @property
    def modified_user(self):
        return self._cleansed_username(self.modified_by)

    @property
    def has_public_barrier(self):
        return hasattr(self, 'public_barrier')

    @property
    def has_wto_profile(self):
        return hasattr(self, 'wto_profile')

    @property
    def is_resolved(self):
        return self.status == BarrierStatus.RESOLVED_IN_FULL

    def last_seen_by(self, user_id):
        try:
            hit = BarrierUserHit.objects.get(user=user_id, barrier=self)
            return hit.last_seen
        except BarrierUserHit.DoesNotExist:
            return None

    def archive(self, user, reason="", explanation=""):
        try:
            if self.public_barrier.public_view_status == PublicBarrierStatus.PUBLISHED:
                raise ArchivingException(
                    "Public barrier should be unpublished first.")
        except PublicBarrier.DoesNotExist:
            pass
        self.archived_explanation = explanation
        self.unarchived_by = None
        self.unarchived_on = None
        self.unarchived_reason = ""
        super().archive(user, reason)

    def save(self,
             force_insert=False,
             force_update=False,
             using=None,
             update_fields=None):
        """
        Upon creating new item, generate a readable reference code
        """
        if self.code is None:
            loop_num = 0
            unique = False
            while not unique:
                if loop_num < settings.REF_CODE_MAX_TRIES:
                    new_code = random_barrier_reference()
                    if not Barrier.objects.filter(code=new_code):
                        self.code = new_code
                        unique = True
                    loop_num += 1
                else:
                    raise ValueError(
                        "Error generating a unique reference code.")

        if self.source != BARRIER_SOURCE.OTHER:
            self.other_source = ""

        if self.caused_by_trading_bloc is not None and not self.country_trading_bloc:
            self.caused_by_trading_bloc = None

        super().save(force_insert, force_update, using, update_fields)
Ejemplo n.º 29
0
class User(AbstractBaseUser, PermissionsMixin):

    email = models.EmailField(
        verbose_name=_('email address'),
        max_length=255, unique=True, db_index=True,
    )
    speaker_name = models.CharField(
        verbose_name=_('speaker name'),
        max_length=100,
    )
    bio = EAWTextField(
        verbose_name=_('biography'),
        max_length=1000,
        help_text=_(
            "Describe yourself with 500 characters or less. "
            "There will be no formatting."
        ),
    )
    photo = models.ImageField(
        verbose_name=_('photo'),
        blank=True, default='', upload_to=photo_upload_to,
    )
    facebook_profile_url = models.URLField(
        verbose_name=_('Facebook'),
        blank=True,
        help_text=format_html_lazy(_(
            "Link to your Facebook profile page. This will be shown when "
            "we display your public information. If you do not know what your "
            "profile page link is, click on "
            "<a href='https://www.facebook.com/me' target='_blank'>"
            "this link</a>, and copy-paste the URL of the page opened. "
            "Remember to log in to Facebook first!"
        )),
    )
    twitter_id = models.CharField(
        verbose_name=_('Twitter'),
        blank=True, max_length=100, validators=[
            RegexValidator(r'^[0-9a-zA-Z_]*$', 'Not a valid Twitter handle'),
        ],
        help_text=_(
            "Your Twitter handle, without the \"@\" sign. This will be "
            "shown when we display your public information."
        ),
    )
    github_id = models.CharField(
        verbose_name=_('GitHub'),
        blank=True, max_length=100, validators=[
            RegexValidator(r'^[0-9a-zA-Z_-]*$', 'Not a valid GitHub account'),
        ],
        help_text=_(
            "Your GitHub account, without the \"@\" sign. This will be "
            "shown when we display your public information."
        ),
    )
    verified = models.BooleanField(
        verbose_name=_('verified'),
        default=False,
        help_text=_(
            "Designates whether the user has verified email ownership."
        ),
    )
    is_staff = models.BooleanField(
        verbose_name=_('staff status'),
        default=False,
        help_text=_(
            "Designates whether the user can log into this admin site."
        ),
    )
    is_active = models.BooleanField(
        verbose_name=_('active'),
        default=True,
        help_text=_(
            "Designates whether this user should be treated as "
            "active. Unselect this instead of deleting accounts."
        ),
    )
    date_joined = models.DateTimeField(
        verbose_name=_('date joined'),
        default=timezone.now,
    )

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')
        swappable = 'AUTH_USER_MODEL'

    def __str__(self):
        return self.email

    def as_hash(self):
        """Return the user's hash representation.

        Pipeline:
            - pk -> md5 -> first 2 bytes -> b16 -> str.
        """
        return '#{hash_user}'.format(
            hash_user=(
                base64.b16encode(
                    # Picking the first 2 bytes may still run into hash
                    # collisions if you take the whole users list into account,
                    # but as this is used for representing reviewers which is a
                    # comparatively small subset, it's not a big deal.
                    hashlib.md5(str(self.pk).encode('utf-8')).digest()[:2],
                ).decode('utf-8')
            )
        )

    as_hash.short_description = _('Reviewer ID')

    def get_full_name(self):
        return self.speaker_name

    def get_short_name(self):
        return self.speaker_name

    def get_photo_url(self):
        """Return the photo URL if set, otherwise a default image.
        """
        if self.photo:
            return self.photo.url
        return static('images/default_head.png')

    def is_valid_speaker(self):
        """Whether the user is a valid speaker.

        :seealso: ``UserQuerySet.get_valid_speakers``
        """
        return (
            self.verified and self.is_active and
            self.speaker_name and self.bio
        )

    def is_reviewer(self):
        return self.has_perm('reviews.add_review')

    @property
    def cospeaking_info_set(self):
        return self.additionalspeaker_set.filter(
            cancelled=False,
            conference=settings.CONFERENCE_DEFAULT_SLUG,
        )

    @property
    def twitter_profile_url(self):
        return 'https://twitter.com/{}'.format(self.twitter_id)

    @property
    def github_profile_url(self):
        return 'https://github.com/{}'.format(self.github_id)

    def get_verification_key(self):
        key = signing.dumps(
            obj=getattr(self, self.USERNAME_FIELD),
            salt=settings.SECRET_KEY,
        )
        return key

    def email_user(self, subject, message, from_email=None, **kwargs):
        """Send an email to this user.
        """
        send_mail(subject, message, from_email, [self.email], **kwargs)

    def send_verification_email(self, request):
        verification_key = self.get_verification_key()
        verification_url = request.build_absolute_uri(
            reverse('user_verify', kwargs={
                'verification_key': verification_key,
            }),
        )
        context = {
            'user': self,
            'host': request.get_host(),
            'verification_key': verification_key,
            'verification_url': verification_url,
        }
        message = render_to_string(
            'registration/verification_email.txt', context,
        )
        self.email_user(
            subject=ugettext('Verify your email address on {host}').format(
                **context
            ),
            message=message, fail_silently=False,
        )
Ejemplo n.º 30
0
class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('billing', '0001_initial'),
        ('insuranceplans', '0001_initial'),
        ('carts', '0001_initial'),
        ('addresses', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Order',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('order_id', models.CharField(blank=True, max_length=120)),
                ('shipping_address_final',
                 models.TextField(blank=True, null=True)),
                ('billing_address_final',
                 models.TextField(blank=True, null=True)),
                ('status',
                 models.CharField(choices=[('created', 'Created'),
                                           ('paid', 'Paid'),
                                           ('shipped', 'Shipped'),
                                           ('refunded', 'Refunded')],
                                  default='created',
                                  max_length=120)),
                ('shipping_total',
                 models.DecimalField(decimal_places=2,
                                     default=5.99,
                                     max_digits=100)),
                ('total',
                 models.DecimalField(decimal_places=2,
                                     default=0.0,
                                     max_digits=100)),
                ('active', models.BooleanField(default=True)),
                ('updated', models.DateTimeField(auto_now=True)),
                ('timestamp', models.DateTimeField(auto_now_add=True)),
                ('billing_address',
                 models.ForeignKey(blank=True,
                                   null=True,
                                   on_delete=django.db.models.deletion.CASCADE,
                                   related_name='billing_address',
                                   to='addresses.address')),
                ('billing_profile',
                 models.ForeignKey(blank=True,
                                   null=True,
                                   on_delete=django.db.models.deletion.CASCADE,
                                   to='billing.billingprofile')),
                ('cart',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='carts.cart')),
                ('shipping_address',
                 models.ForeignKey(blank=True,
                                   null=True,
                                   on_delete=django.db.models.deletion.CASCADE,
                                   related_name='shipping_address',
                                   to='addresses.address')),
            ],
            options={
                'ordering': ['-timestamp', '-updated'],
            },
        ),
        migrations.CreateModel(
            name='InsuranceplanPurchase',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('order_id', models.CharField(max_length=120)),
                ('refunded', models.BooleanField(default=False)),
                ('updated', models.DateTimeField(auto_now=True)),
                ('timestamp', models.DateTimeField(auto_now_add=True)),
                ('billing_profile',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='billing.billingprofile')),
                ('insuranceplan',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='insuranceplans.insuranceplan')),
            ],
        ),
    ]