Exemplo n.º 1
0
class Location(Model):
    building = CharField(max_length=60)
    building_number = CharField(max_length=4)
    room_number = CharField(max_length=4)
    has_equipment = BooleanField(default=False)
    capacity = PositiveSmallIntegerField()

    def __unicode__(self):
        return self.building + " (" + self.building_number + ") " + self.room_number

    class Meta:
        unique_together = ("building_number", "room_number")
Exemplo n.º 2
0
    def contribute_to_class(self, cls, name):
        if hasattr(cls._meta, "birthday_field"):
            raise FieldError(
                "django-birthday does not support multiple BirthdayFields on a single model"
            )
        cls._meta.birthday_field = self

        self.doy_name = "%s_dayofyear_internal" % name

        if not hasattr(cls, self.doy_name):
            dayofyear_field = PositiveSmallIntegerField(editable=False,
                                                        default=None,
                                                        null=True)
            # print("dayofyear_field", dayofyear_field)
            dayofyear_field.creation_counter = self.creation_counter

            cls.add_to_class(self.doy_name, dayofyear_field)

        super(BirthdayField, self).contribute_to_class(cls, name)

        pre_save.connect(pre_save_listener, sender=cls)
Exemplo n.º 3
0
class Especialidad(models.Model):
    codigo = PositiveIntegerField()
    nombre = models.CharField(max_length=50)
    cantidad_A = PositiveIntegerField('cantidad de Años')
    tipo = PositiveSmallIntegerField()

    class Meta:
        verbose_name = "Especialidad"
        verbose_name_plural = "Especialidades"

    def __unicode__(self):
        return self.nombre
Exemplo n.º 4
0
class Familia(models.Model):
    name = CharField(max_length=100)
    pos = PositiveSmallIntegerField()
    is_active = BooleanField(default=True)
    created_at = DateTimeField(auto_now_add=True)
    updated_at = DateTimeField(auto_now=True)

    #productos - Producto

    def __str__(self):
        return f"Familia {self.name}, actualmente activa: {self.is_active}"

    objects = MantenedorManager()
Exemplo n.º 5
0
class AnalysisStatus(models.Model):
    OK = 'SUCCESS'
    ERROR = 'FAILURE'
    PROGRESS = 'PROGRESS'
    UNKNOWN = 'PENDING'
    GALAXY_HISTORY_STATES = (
        (OK, 'OK'),
        (ERROR, 'Error'),
        (PROGRESS, 'Running'),
        (UNKNOWN, 'Unknown')
    )
    analysis = models.ForeignKey("core.Analysis")  # prevents circular import
    refinery_import_task_group_id = UUIDField(blank=True, null=True,
                                              auto=False)
    galaxy_import_task_group_id = UUIDField(blank=True, null=True, auto=False)
    galaxy_export_task_group_id = UUIDField(blank=True, null=True, auto=False)
    #: state of Galaxy history
    galaxy_history_state = CharField(max_length=10, blank=True,
                                     choices=GALAXY_HISTORY_STATES)
    #: percentage of successfully processed datasets in Galaxy history
    galaxy_history_progress = PositiveSmallIntegerField(blank=True, null=True)

    def __unicode__(self):
        return self.analysis.name

    def set_galaxy_history_state(self, state):
        if state in dict(self.GALAXY_HISTORY_STATES).keys():
            self.galaxy_history_state = state
            self.save()
        else:
            raise ValueError("Invalid Galaxy history state given")

    def refinery_import_state(self):
        return get_task_group_state(self.refinery_import_task_group_id)

    def galaxy_import_state(self):
        return get_task_group_state(self.galaxy_import_task_group_id)

    def galaxy_analysis_state(self):
        if self.galaxy_history_state and self.galaxy_history_progress:
            galaxy_history_state = [{
                'state': self.galaxy_history_state,
                'percent_done': self.galaxy_history_progress
            }]
        else:
            galaxy_history_state = []
        return galaxy_history_state

    def galaxy_export_state(self):
        return get_task_group_state(self.galaxy_export_task_group_id)
Exemplo n.º 6
0
class Subject(models.Model):
    subject = models.CharField(max_length=250, primary_key=True)
    subject_code = models.CharField(max_length=50)
    subject_year = models.CharField(
        max_length=50,
        choices=YEAR_CHOICES,
        default="1st",
    )
    subject_unit = PositiveSmallIntegerField()
    subject_description = models.TextField()
    subject_course = models.OneToOneField(Course, on_delete=models.CASCADE)

    def __str__(self):
        return self.subject_code
Exemplo n.º 7
0
class Area(models.Model):
    name = CharField(max_length=100)
    pos = PositiveSmallIntegerField()
    is_active = BooleanField(default=True)
    created_at = DateTimeField(auto_now_add=True)
    updated_at = DateTimeField(auto_now=True)

    #users_que_solicitan = models.ManyToManyField(User,related_name='areas_que_solicitan')
    #users_que_autorizan = models.ManyToManyField(User,related_name='areas_que_autorizan')
    #users_que_ejecutan = models.ManyToManyField(User,related_name='areas_que_ejecuta')
    def __str__(self):
        return f"Area {self.name}, actualmente activa: {self.is_active}"

    objects = MantenedorManager()
Exemplo n.º 8
0
class CoursePreference(Model):
    """An instructor's course preference."""

    PREFERENCE_CHOICES = [(x, x) for x in xrange(6)]

    term = ForeignKey(Term)
    instructor = ForeignKey(settings.AUTH_USER_MODEL)
    course = ForeignKey(Course)
    preference = PositiveSmallIntegerField(default=0,
                                           verbose_name='',
                                           choices=PREFERENCE_CHOICES)

    def __unicode__(self):
        return "Course Preference (%s)" % unicode(self.id)
Exemplo n.º 9
0
class CategoriaEvento(Model):
    nombre = CharField('nombre', max_length=100, blank=True, null=True)
    order = PositiveSmallIntegerField(u'orden en cartelera', default=0)
    slug = SlugField(db_index=True)

    def current_events(self):
        today_min = datetime.datetime.combine(date.today(), datetime.time.min)
        return self.eventobase_set.select_related().order_by('start').filter(
            end__gte=today_min)[:20]

    def __unicode__(self):
        return self.nombre

    def get_absolute_url(self):
        return reverse('categoria_evento', kwargs={'slug': self.slug})
Exemplo n.º 10
0
class TipoMov(models.Model):
    name = CharField(max_length=100)
    pos = PositiveSmallIntegerField()
    is_active = BooleanField(default=True)
    created_at = DateTimeField(auto_now_add=True)
    updated_at = DateTimeField(auto_now=True)
    folio = OneToOneField(Folio,
                          related_name="tipo_mov",
                          null=True,
                          on_delete=models.PROTECT)

    def __str__(self):
        return f"TipoMov {self.name}, actualmente activa: {self.is_active}"

    objects = MantenedorManager()
Exemplo n.º 11
0
class Answer(Model):
    """
    A option of a answer collection.

    This model defines the actual value and label
    of a question.
    """
    class Meta:
        ordering = ("order", )
        unique_together = (("answers", "order"), ("answers", "label"))

    label = CharField(max_length=255)
    order = PositiveSmallIntegerField()

    answers = ForeignKey(Answers, CASCADE, "values")
    deleted = DateTimeField(null=True)
Exemplo n.º 12
0
    def contribute_to_class(self, cls, name):
        super(BirthdayField, self).contribute_to_class(cls, name)

        if hasattr(cls._meta, 'birthday_field'):
            raise FieldError(
                "django-birthday does not support multiple BirthdayFields on a single model"
            )
        cls._meta.birthday_field = self

        self.doy_name = '%s_dayofyear_internal' % name
        if not hasattr(cls, self.doy_name):
            PositiveSmallIntegerField(editable=False, default=None,
                                      null=True).contribute_to_class(
                                          cls, self.doy_name)

        pre_save.connect(pre_save_listener, sender=cls)
Exemplo n.º 13
0
class Section(Model):
    course = ForeignKey(Course)
    number = PositiveSmallIntegerField()
    instructor = ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
    location = ForeignKey(Location, null=True, blank=True)
    times = ManyToManyField('SectionTime', blank=True)

    # The associated lab, if it exists
    is_lab = BooleanField(default=False)
    associated_lab = ForeignKey('self', null=True, blank=True)

    def __unicode__(self):
        return unicode(self.course) + " - " + unicode(self.number).zfill(2)

    class Meta:
        unique_together = ("course", "number")
Exemplo n.º 14
0
class ProjectEditorValidation(Model):
    """
    A validation is used to set a certain field or combination of fields in the project editor as
    mandatory, hidden or read only.

    The rule field is the key in this model. There are 2 options for this field:
    - Only a model (e.g. "partnership") indicating that at least one partnership is mandatory or
    that partnerships should be hidden in the project editor.
    - A model and a field (e.g. "budgetitem.other_extra") indicating that the field is mandatory
    or that the field should be hidden in the project editor.

    Also, any combination of the above options is possible. Separated by ||, which
    indicates an OR relationship. So "project.title||project.subtitle" with a mandatory action
    indicates that either the title or the subtitle of a project is mandatory.
    """
    MANDATORY_ACTION = 1
    HIDDEN_ACTION = 2

    ACTIONS_LIST = [
        MANDATORY_ACTION,
        HIDDEN_ACTION,
    ]

    ACTIONS_LABELS = [
        _('Mandatory'),
        _('Hidden'),
    ]

    ACTIONS = list(zip(ACTIONS_LIST, ACTIONS_LABELS))

    validation_set = ForeignKey(ProjectEditorValidationSet,
                                on_delete=models.CASCADE,
                                verbose_name=_('validation set'),
                                related_name='validations')
    validation = CharField(_('validation'), max_length=255)
    action = PositiveSmallIntegerField(_('action'),
                                       choices=ACTIONS,
                                       db_index=True)

    def __str__(self):
        return "{0} ({1})".format(self.validation,
                                  str(dict(self.ACTIONS)[self.action]))

    class Meta:
        app_label = 'rsr'
        verbose_name = _('project editor validation')
        verbose_name_plural = _('project editor validations')
Exemplo n.º 15
0
class AccessPoint(NetworkDevice):
    """Access Point"""

    property_id = CharField(max_length=7,
                            unique=True,
                            verbose_name='Property ID')
    serial_number = CharField(max_length=9,
                              unique=True,
                              verbose_name='Serial Number')
    ap_type = PositiveSmallIntegerField(choices=AP_TYPE_CHOICES,
                                        verbose_name='Type')

    def clean(self):
        if not self.upstream_device:
            raise ValidationError(
                'An upstream device is required for access points.')
        super().clean()
Exemplo n.º 16
0
class UnidadMedida(models.Model):
    name = CharField(max_length=100)
    pos = PositiveSmallIntegerField()
    is_active = BooleanField(default=True)
    created_at = DateTimeField(auto_now_add=True)
    updated_at = DateTimeField(auto_now=True)
    tipo_medida = models.OneToOneField(TipoMedida,
                                       related_name="unidad_medida",
                                       null=True,
                                       on_delete=models.PROTECT)

    def __str__(self):
        return f"Unidad medida {self.name}, de tipo medida {self.tipo_medida} actualmente activa: {self.is_active}"

    #productos - Producto

    objects = MantenedorManager()
Exemplo n.º 17
0
class Issue(models.Model):
    class Status(models.IntegerChoices):
        OPEN = 1, 'Open'
        CLOSED = 2, 'Closed'
        MERGED = 3, 'Merged'

    author = ForeignKey(User, on_delete=SET_NULL, null=True)
    project = ForeignKey(Project, on_delete=CASCADE, related_name='issues')
    title = CharField(max_length=50, blank=False)
    description = CharField(max_length=300)
    created_at = DateTimeField(auto_now_add=True)
    updated_at = DateTimeField(auto_now=True)
    status = PositiveSmallIntegerField(default=Status.OPEN,
                                       choices=Status.choices)
    label = ForeignKey(Label, on_delete=SET_NULL, null=True)

    assignees = ManyToManyField(User,
                                through='Assignee',
                                related_name='issues')

    def __str__(self):
        return self.title
Exemplo n.º 18
0
class Customer(models.Model):
    number = CharField(max_length=32, unique=True)
    name = CharField(max_length=128)
    type = PositiveSmallIntegerField(choices=CUSTOMER_TYPE_CHOICES,
                                     default=COMPANY)
    address = models.ForeignKey(Address,
                                blank=True,
                                null=True,
                                on_delete=PROTECT,
                                related_name='customer')
    shipping_address = models.ForeignKey(Address,
                                         blank=True,
                                         null=True,
                                         on_delete=PROTECT,
                                         related_name='customer_ship')
    billing_address = models.ForeignKey(Address,
                                        blank=True,
                                        null=True,
                                        on_delete=PROTECT,
                                        related_name='customer_bill')

    def __str__(self):
        return self.number + ' - ' + self.name
Exemplo n.º 19
0
 def test_PositiveSmallIntegerField(self):
     self.assertIsInstance(PositiveSmallIntegerField().get_prep_value(1),
                           int)
Exemplo n.º 20
0
class Ethernet(models.Model):
    author = models.ForeignKey('auth.User')
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=10,
                            unique=True,
                            blank=False,
                            null=False,
                            default=None)
    desc = models.CharField(max_length=80, blank=True, null=True, default=None)
    status = models.BooleanField(default=True)
    dhcp = models.BooleanField(default=False)
    link = models.BooleanField(default=True)
    mac = models.CharField(max_length=17, blank=True, null=True, default=None)
    ipv4address = models.CharField(max_length=240,
                                   blank=True,
                                   null=True,
                                   default=None)
    gateway = models.CharField(max_length=255,
                               blank=True,
                               null=True,
                               default=None)
    manual_dns = models.BooleanField(default=True)
    dnsserver = models.CharField(max_length=32,
                                 blank=True,
                                 null=True,
                                 default=None)
    mtu = PositiveSmallIntegerField(blank=False, null=False, default="1500")
    manual_mss = models.BooleanField(default=False)
    mss = PositiveSmallIntegerField(blank=True, null=True, default="1460")
    added_date = models.CharField(max_length=25)
    edited_date = models.CharField(max_length=25,
                                   blank=True,
                                   null=True,
                                   default=None)

    def edit(self):
        self.save()

    def __str__(self):
        return self.desc

    def __unicode__(self):
        return self.desc

    def save(self,
             force_insert=False,
             force_update=False,
             using=None,
             update_fields=None):
        shutdown(self)
        removeNetworkConfigurationOf(self)
        models.Model.save(self,
                          force_insert=force_insert,
                          force_update=force_update,
                          using=using,
                          update_fields=update_fields)
        setNetworkConfigurationOf(self)
        startup(self)

    def delete(self, using=None):
        shutdown(self)
        removeNetworkConfigurationOf(self)
        models.Model.delete(self, using=using)
Exemplo n.º 21
0
class ResidenciaAut(models.Model):
    tipo_choice = (
        ('C', 'Colegio'),
        ('M', 'Mixta'),
    )

    expediente = models.CharField('N° de Expediente del Ministerio de Salud',
                                  max_length=12,
                                  null=True,
                                  blank=True,
                                  default='0-0-00',
                                  help_text='####-####/##')
    a_Comienzo = PositiveSmallIntegerField('Año')
    especialidad = models.ForeignKey(Especialidad,
                                     related_name='+',
                                     null=True,
                                     blank=True)
    institucion = models.ForeignKey('Institucion',
                                    related_name='+',
                                    null=True,
                                    blank=True)
    cantA_1 = PositiveSmallIntegerField('1er. Año')
    cantA_2 = PositiveSmallIntegerField('2do. Año')
    cantA_3 = PositiveSmallIntegerField('3er. Año')
    cantA_4 = PositiveSmallIntegerField('4to. Año')
    jefeResidentes = PositiveSmallIntegerField('Jefe de Residentes')
    fechaEvaluacColMed = DateField('Fecha de Evaluación',
                                   blank=True,
                                   null=False)
    fechaEvaluacMixta = DateField('Fecha de Evaluación Mixta',
                                  blank=True,
                                  null=True)
    fechaCeseActividad = DateField('Fecha de Vencimiento Acreditación',
                                   blank=True,
                                   null=True)
    jefeServicio = models.CharField('Jefe de Servicio',
                                    max_length=50,
                                    blank=True,
                                    null=True)
    coordinador = models.CharField('Coordinador',
                                   max_length=50,
                                   blank=True,
                                   null=True)
    asesorDocente = models.CharField('Asesor Docente',
                                     max_length=150,
                                     blank=True)
    jefedocencia = models.CharField('Jefe Docencia',
                                    max_length=150,
                                    blank=True)
    tipo = models.CharField(max_length=2, choices=tipo_choice, blank=True)
    memo = models.TextField('memo', null=True, blank=True)
    instructorr = models.CharField('Instructor de Residentes',
                                   max_length=150,
                                   blank=True)

    class Meta:
        verbose_name = "Residencia"
        verbose_name_plural = "Residencias"

    def __unicode__(self):
        return unicode(self.a_Comienzo)

    def fechaEvalNoNula(self):
        if not self.fechaEvaluacColMed:
            return ''
        else:
            return self.fechaEvaluacColMed.strftime("%d/%m/%Y")

    def fechaCeseActividadNoNula(self):
        if not self.fechaCeseActividad:
            return ''
        else:
            return self.fechaCeseActividad.strftime("%d/%m/%Y")

    def memoNoNulo(self):
        if not self.memo:
            return '.'
        else:
            return self.memo

    def nombreTipo(self):
        if self.tipo == 'C':
            return 'Colegio'
        else:
            return 'Mixto'

    def sumaCantA(self):
        return self.cantA_1 + self.cantA_2 + self.cantA_3 + self.cantA_4
Exemplo n.º 22
0
class Term(Model):

    SEASONS = ['Fall', 'Winter', 'Spring', 'Summer']
    SEASON_CHOICES = [(SEASONS.index(season), season) for season in SEASONS]

    season_index = IntegerField(choices=SEASON_CHOICES)
    year = PositiveSmallIntegerField()
    schedule = ForeignKey(Schedule, null=True, blank=True)
    preferences_lock_date = DateField()
    votes_lock_date = DateField()

    def __unicode__(self):
        return self.SEASONS[self.season_index] + " " + unicode(self.year)

    @property
    def preferences_locked(self):
        today = datetime.date.today()

        if today >= self.preferences_lock_date:
            return True

        return False

    @property
    def votes_locked(self):
        today = datetime.date.today()

        if today >= self.votes_lock_date:
            return True

        return False

    def get_or_create_current_term(self):
        today = datetime.date.today()

        # Convert date to month and day as integer (md), e.g. 4/21 = 421, 11/17 = 1117, etc.
        # See: http://stackoverflow.com/questions/16139306/determine-season-given-timestamp-in-python-using-datetime
        year = today.year
        month = today.month * 100
        day = today.day
        monthday = month + day

        if monthday >= 921 and monthday <= 1231:
            season = self.SEASONS.index("Fall")
            lock_date = datetime.date(year, 11, 1)
        elif monthday >= 11 and monthday <= 320:
            season = self.SEASONS.index("Winter")
            lock_date = datetime.date(year, 2, 1)
        elif monthday >= 321 and monthday <= 620:
            season = self.SEASONS.index("Spring")
            lock_date = datetime.date(year, 5, 1)
        elif monthday >= 621 and monthday <= 920:
            season = self.SEASONS.index("Summer")
            lock_date = datetime.date(year, 8, 1)
        else:
            season = None
            lock_date = None

        if season:
            try:
                term = Term.objects.get(season_index=season, year=year)
            except Term.DoesNotExist:
                new_term = Term(season_index=season, year=year)
                new_term.votes_lock_date = lock_date
                new_term.preferences_lock_date = lock_date
                new_term.save()

                term = new_term

        return term

    class Meta:
        unique_together = ("season_index", "year")
Exemplo n.º 23
0
class AnalysisStatus(models.Model):
    OK = 'SUCCESS'
    ERROR = 'FAILURE'
    PROGRESS = 'PROGRESS'
    UNKNOWN = 'PENDING'
    GALAXY_HISTORY_STATES = (
        (OK, 'OK'),
        (ERROR, 'Error'),
        (PROGRESS, 'Running'),
        (UNKNOWN, 'Unknown')
    )
    analysis = models.ForeignKey("core.Analysis")  # prevents circular import
    refinery_import_task_group_id = models.UUIDField(null=True, editable=False)
    galaxy_import_task_group_id = models.UUIDField(null=True, editable=False)
    galaxy_export_task_group_id = models.UUIDField(null=True, editable=False)
    galaxy_workflow_task_group_id = models.UUIDField(null=True, editable=False)
    #: state of Galaxy file imports
    galaxy_import_state = CharField(max_length=10, blank=True,
                                    choices=GALAXY_HISTORY_STATES)
    #: state of Galaxy history
    galaxy_history_state = CharField(max_length=10, blank=True,
                                     choices=GALAXY_HISTORY_STATES)

    #: percentage of successfully imported datasets in Galaxy history
    galaxy_import_progress = PositiveSmallIntegerField(default=0)

    #: percentage of successfully processed datasets in Galaxy history
    # TODO: refactor `galaxy_history_progress` to take advantage of a
    # default value of 0, and
    galaxy_history_progress = PositiveSmallIntegerField(blank=True, null=True)

    class Meta:
        verbose_name_plural = 'analysis statuses'

    def __unicode__(self):
        return self.analysis.name

    def set_galaxy_history_state(self, state):
        """
        Set the `galaxy_history_state` of an analysis
        :param state: a valid GALAXY_HISTORY_STATE
        """
        if state in dict(self.GALAXY_HISTORY_STATES).keys():
            self.galaxy_history_state = state
            self.save()
        else:
            raise ValueError("Invalid Galaxy history state given")

    def set_galaxy_import_state(self, state):
        """
        Set the `galaxy_import_state` of an analysis
        :param state: a valid GALAXY_HISTORY_STATE
        """
        if state in dict(self.GALAXY_HISTORY_STATES).keys():
            self.galaxy_import_state = state
            self.save()
        else:
            raise ValueError("Invalid Galaxy history state given")

    def refinery_import_state(self):
        if self.analysis.has_all_local_input_files():
            return [{'state': celery.states.SUCCESS, 'percent_done': 100}]
        else:
            return get_task_group_state(self.refinery_import_task_group_id)

    def galaxy_file_import_state(self):
        if self.galaxy_import_state and self.galaxy_import_progress != 0:
            galaxy_file_import_state = [{
                'state': self.galaxy_import_state,
                'percent_done': self.galaxy_import_progress
            }]
        else:
            galaxy_file_import_state = []
        return galaxy_file_import_state

    def galaxy_analysis_state(self):
        if self.galaxy_history_state and self.galaxy_history_progress:
            galaxy_history_state = [{
                'state': self.galaxy_history_state,
                'percent_done': self.galaxy_history_progress
            }]
        else:
            galaxy_history_state = []
        return galaxy_history_state

    def galaxy_export_state(self):
        return get_task_group_state(self.galaxy_export_task_group_id)

    def set_galaxy_import_task_group_id(self, galaxy_import_task_group_id):
        self.galaxy_import_task_group_id = galaxy_import_task_group_id
        self.save()

    def set_galaxy_workflow_task_group_id(self, galaxy_workflow_task_group_id):
        self.galaxy_workflow_task_group_id = galaxy_workflow_task_group_id
        self.save()
Exemplo n.º 24
0
class GraphElementTemplate(BaseGraphTemplate):
    """
    GraphElementTemplate class - inherits from BaseGraphTemplate
    JSON Format is used.
    Attributes implemented for this dict are:

    "type":      "line",
    "colour":    "#9933CC",
    "text":      "Page views",
    "width":     2,
    "font-size": 10,
    "dot-size":  6,
    "values" :   [15,18,19,14,17,18,15,18,17]

    """
    type = CharField(max_length=255,
                     verbose_name=_('Type'),
                     choices=GRAPH_TYPE_CHOICES)
    fk_graph_template = ForeignKey('GraphTemplate',
                                   related_name='graph_elements')
    alpha = FloatField(verbose_name=_('Alpha'),
                       blank=True,
                       null=True,
                       default=0.5)
    colour = ColorField(verbose_name=_('Colour'), blank=True, null=True)
    text = CharField(max_length=255,
                     verbose_name=_('Text'),
                     blank=True,
                     null=True)
    width = PositiveSmallIntegerField(verbose_name=_('Width'))
    font_size = PositiveSmallIntegerField(verbose_name=_('Font Size'))
    dot_size = PositiveSmallIntegerField(verbose_name=_('Dot Size'))
    tooltip = CharField(
        max_length=100,
        verbose_name=_('Tooltip'),
        default=_('#val#'),
        help_text=_('Use some keywords like #val# Example: value:#val#'))
    inspection = CharField(max_length=255,
                           verbose_name=_('Ispect'),
                           choices=INSPECTION_DATE_CHOICES,
                           default='self')
    dot_style_type = CharField(max_length=255,
                               verbose_name=_('Dot-Style Type'),
                               choices=DOT_STYLE_CHOICES,
                               blank=True,
                               null=True)
    dot_style_dot_size = PositiveSmallIntegerField(
        verbose_name=_('Dot-Style Size'), blank=True, null=True)
    dot_style_colour = ColorField(verbose_name=_('Dot-Style Colour'),
                                  blank=True,
                                  null=True)
    dot_style_halo_size = PositiveSmallIntegerField(
        verbose_name=_('Dot-Style Halo Size'), blank=True, null=True)
    graph_element_json = CharField(max_length=1024,
                                   verbose_name=_('Element JSON'),
                                   blank=True,
                                   null=True)

    values = []

    class Meta:
        """
        Meta class
        """
        #app_label   = 'graphs'
        verbose_name = _('Graph Template Element')
        verbose_name_plural = _('Graph Template Elements')

    def set_values_in_object(self, obj, vl):
        """
        This method set the values for a graph element object
        obj - the element object where the values have to be set
        vl - the list of values
        """
        obj['values'] = vl

    def set_element_values(self, vl):
        """
        This method set the values for a graph element,
        setting the corresponding attribute.
        vl - the list of values to be set
        """
        self.values = vl

    def build_dot_style(self):
        """
        """
        ds = dict()
        ds['dot-style'] = dict()
        if self.dot_style_type: ds['dot-style']['type'] = self.dot_style_type
        if self.dot_style_dot_size:
            ds['dot-style']['dot-size'] = self.dot_style_dot_size
        if self.dot_style_halo_size:
            ds['dot-style']['halo-size'] = self.dot_style_halo_size
        if self.dot_style_colour:
            ds['dot-style']['colour'] = self.dot_style_colour
        if self.tooltip: ds['dot-style']['tip'] = self.tooltip
        return ds

    def build_obj_element(self):
        obj = dict()
        obj['values'] = []
        if self.type:
            t = self.type
            if self.type == 'linedot':
                t = 'line'
            obj['type'] = t

            if self.colour: obj['colour'] = '#%s' % self.colour
            if self.alpha: obj['alpha'] = self.alpha
            if self.text: obj['text'] = str(self.text)
            if self.width: obj['width'] = self.width
            if self.font_size: obj['font-size'] = self.font_size
            if self.dot_size: obj['dot-size'] = self.dot_size
            if t == 'line':
                dst = self.build_dot_style()
                obj.update(dst)
            else:
                if self.tooltip: obj['tip'] = self.tooltip
        if len(self.values) > 0:
            obj['values'] = self.values
        return obj

    def to_json(self):
        """
        This method returns a json given a dict object
        return - json object built from obj
        """
        obj = self.build_obj_element()
        return simplejson.dumps(obj)

    def __unicode__(self):
        """
        This the unicode method
        """
        return u'%s' % self.name

    def save(self, *args, **kwargs):
        """
        This is just the save method, crate a json and save it in the corresponding field
        """
        self.graph_element_json = self.to_json()
        super(GraphElementTemplate, self).save(*args, **kwargs)
Exemplo n.º 25
0
class ResidenciaAut(models.Model):
    tipo_choice = (
        ('C', 'Colegio'),
        ('M', 'Mixta'),
    )
    tipoI_choice = (
        ('U', 'Pública'),
        ('P', 'Privada'),
    )
    tipoInst = models.CharField(max_length=2,
                                choices=tipoI_choice,
                                blank=False,
                                default='P')
    expediente = models.CharField('N° de Expediente del Ministerio de Salud',
                                  max_length=12,
                                  null=True,
                                  blank=True,
                                  default='0-0-00',
                                  help_text='####-####/##')
    a_Comienzo = PositiveSmallIntegerField('Año')
    especialidad = models.ForeignKey(Especialidad,
                                     related_name='+',
                                     null=True,
                                     blank=True)
    institucion = models.ForeignKey('Institucion',
                                    related_name='+',
                                    null=True,
                                    blank=True)
    cantA_1 = PositiveSmallIntegerField('1er. Año')
    cantA_2 = PositiveSmallIntegerField('2do. Año')
    cantA_3 = PositiveSmallIntegerField('3er. Año')
    cantA_4 = PositiveSmallIntegerField('4to. Año')
    jefeResidentes = PositiveSmallIntegerField('Jefe de Residentes')
    fechaEvaluacColMed = DateField('Fecha de Evaluación',
                                   blank=True,
                                   null=False)
    fechaEvaluacMixta = DateField('Fecha de Evaluación Mixta',
                                  blank=True,
                                  null=True)
    fechaCeseActividad = DateField('Fecha de Vencimiento Acreditación',
                                   blank=True,
                                   null=True)
    jefeServicio = models.CharField('Jefe de Servicio',
                                    max_length=50,
                                    blank=True,
                                    null=True)
    coordinador = models.CharField('Coordinador',
                                   max_length=50,
                                   blank=True,
                                   null=True)
    asesorDocente = models.CharField('Asesor Docente',
                                     max_length=150,
                                     blank=True)
    tipo = models.CharField(max_length=2, choices=tipo_choice, blank=True)
    memo = models.TextField('memo', null=True, blank=True)
    jefedocencia = models.CharField('Jefe Docencia',
                                    max_length=150,
                                    blank=True)
    instructor = models.CharField('Instructor de Residentes',
                                  max_length=150,
                                  blank=True)

    class Meta:
        verbose_name = "Residencia"
        verbose_name_plural = "Residencias"

    ordering = ["a_Comienzo"]

    def getDirector(self):
        return self.institucion.director

    getDirector.short_description = ("Director")

    def get_absolute_url(self):
        return u'/edita/%d' % self.id

    def __unicode__(self):
        return unicode(self.a_Comienzo)

    def fechaEvalNoNula(self):
        if not self.fechaEvaluacColMed:
            return ''
        else:
            return self.fechaEvaluacColMed.strftime("%d/%m/%Y")

    def fechaCeseActividadNoNula(self):
        if not self.fechaCeseActividad:
            return ''
        else:
            return self.fechaCeseActividad.strftime("%d/%m/%Y")

    def memoNoNulo(self):
        if not self.memo:
            return '.'
        else:
            return self.memo

    def nombreTipo(self):
        if self.tipo == 'C':
            return 'Colegio'
        else:
            return 'Mixto'

    def sumaCantA(self):
        return self.cantA_1 + self.cantA_2 + self.cantA_3 + self.cantA_4 + self.jefeResidentes

    def sumaGral(self):
        return sum(self.cantA_1)

    def getInstitucion(self):
        if not self.institucion:
            return ''
        else:
            return self.institucion.nombre

    def getEspecialidad(self):
        if not self.especialidad:
            return ''
        else:
            return self.especialidad.nombre

    def getJefeServicio(self):
        if not self.jefeServicio:
            return ''
        else:
            return self.jefeServicio

    def getJefeDocencia(self):
        if not self.jefedocencia:
            return ''
        else:
            return self.jefedocencia

    def getAsesorDocente(self):
        if not self.asesorDocente:
            return ''
        else:
            return self.asesorDocente

    def getCoordinador(self):
        if not self.coordinador:
            return ''
        else:
            return self.coordinador

    def getInstructor(self):
        if not self.instructor:
            return ''
        else:
            return self.instructor
Exemplo n.º 26
0
from django.core.exceptions import FieldError
from django.db.models.fields import PositiveSmallIntegerField, DateField
from django.db.models.signals import pre_save

internal_field = PositiveSmallIntegerField(editable=False,
                                           default=None,
                                           null=True)


def pre_save_listener(instance, **kwargs):
    field = instance._meta.birthday_field
    birthday = getattr(instance, field.name)
    if not birthday:
        return
    doy = birthday.timetuple().tm_yday
    setattr(instance, field.doy_name, doy)


class BirthdayField(DateField):
    def contribute_to_class(self, cls, name):
        super(BirthdayField, self).contribute_to_class(cls, name)
        if hasattr(cls._meta, 'birthday_field'):
            raise FieldError("django-birthday does not support multiple "
                             "BirthdayFields on a single model.")
        cls._meta.birthday_field = self
        self.doy_name = '%s_dayofyear_internal' % name
        internal_field.contribute_to_class(cls, self.doy_name)
        pre_save.connect(pre_save_listener, sender=cls)
Exemplo n.º 27
0
 def test_PositiveSmallIntegerField(self):
     lazy_func = lazy(lambda: 1, int)
     self.assertIsInstance(
         PositiveSmallIntegerField().get_prep_value(lazy_func()), int)
Exemplo n.º 28
0
class TipoMedida(models.Model):
    #unidad_medida - UnidadMedida
    decimales = PositiveSmallIntegerField()

    def __str__(self):
        return f"Tipo medida con {self.decimales} decimales"