Ejemplo n.º 1
0
class Hypothesis(models.Model):
    """An ACH matrix hypothesis."""

    board = models.ForeignKey(Board, on_delete=models.CASCADE)
    hypothesis_text = models.CharField(
        'hypothesis',
        max_length=HYPOTHESIS_MAX_LENGTH
    )
    creator = models.ForeignKey(User, null=True)
    submit_date = models.DateTimeField('date added', auto_now_add=True)
    removed = models.BooleanField(default=False)
    field_history = FieldHistoryTracker(['hypothesis_text', 'removed'])

    objects = RemovableModelManager()
    all_objects = models.Manager()

    class Meta:  # pylint: disable=too-few-public-methods
        """Hypothesis Model meta options.

        For more information, please see:
            https://docs.djangoproject.com/en/1.10/topics/db/models/#meta-options
        """

        verbose_name_plural = _("hypotheses")

    def __str__(self):
        """Return a human-readable representation of the hypothesis."""
        return self.hypothesis_text
Ejemplo n.º 2
0
class Eq_Vid(models.Model):
    no_Serie_Vid = models.CharField(primary_key=True,
                                    max_length=30,
                                    verbose_name="No. de Serie")
    nombre_Vid = models.CharField(max_length=30, verbose_name="Nombre")
    marca = models.CharField(max_length=10)
    modelo_Vid = models.CharField(max_length=30, verbose_name="Modelo")
    field_history = FieldHistoryTracker(['Status'])
    Status_Choice = (
        ("disponible", "disponible"),
        ("servicio", "servicio"),
        ("reparacion", "reparación"),
        ("destruccion", "destruccion"),
    )
    Status = models.CharField(max_length=15, choices=Status_Choice)
    qr_code = models.ImageField(upload_to='qr_codes', blank=True)

    def __str__(self):
        return self.no_Serie_Vid

    def save(self, *args, **kwargs):
        qrcode_img = qrcode.make(self.no_Serie_Vid)
        canvas = Image.new('RGB', (290, 290), 'white')
        draw = ImageDraw.Draw(canvas)
        canvas.paste(qrcode_img)
        fno_Serie_Vid = f'qr_code-{self.no_Serie_Vid}.png'
        buffer = BytesIO()
        canvas.save(buffer, 'PNG')
        self.qr_code.save(fno_Serie_Vid, File(buffer), save=False)
        canvas.close()
        super().save(*args, **kwargs)

    class Meta:
        verbose_name = 'Equipo de video'
        verbose_name_plural = 'Equipo de video'
Ejemplo n.º 3
0
class Owner(Person):
    pet = models.ForeignKey(Pet,
                            blank=True,
                            null=True,
                            on_delete=models.CASCADE)

    field_history = FieldHistoryTracker(['name', 'pet'])
Ejemplo n.º 4
0
class Evidence(models.Model):
    """A piece of evidence for an ACH matrix."""

    board = models.ForeignKey(Board, on_delete=models.CASCADE)
    creator = models.ForeignKey(User, null=True)
    evidence_desc = models.CharField('evidence description',
                                     max_length=EVIDENCE_MAX_LENGTH)
    event_date = models.DateField('evidence event date', null=True)
    submit_date = models.DateTimeField('date added')
    removed = models.BooleanField(default=False)
    field_history = FieldHistoryTracker(
        ['evidence_desc', 'event_date', 'removed'])

    objects = RemovableModelManager()
    all_objects = models.Manager()

    class Meta:  # pylint: disable=too-few-public-methods
        """Evidence Model meta options.

        For more information, please see:
            https://docs.djangoproject.com/en/1.10/topics/db/models/#meta-options
        """

        verbose_name_plural = "evidence"

    def __str__(self):
        """Return a human-readable representation of the evidence."""
        return self.evidence_desc

    def get_canonical_url(self):
        """Return the canonical URL for view evidence details."""
        return reverse('openach:evidence_detail', args=(self.id, ))
Ejemplo n.º 5
0
Archivo: models.py Proyecto: gahan9/mdb
class Genres(models.Model):
    genre_id = models.IntegerField(unique=True)
    genre_name = models.CharField(max_length=256)
    poster_path = models.URLField(
        max_length=1000,
        verbose_name=_("Thumbnail"),
        help_text=_("Enter image URL of resolution width 300"),
        blank=True,
        null=True)
    backdrop_path = models.URLField(
        max_length=1000,
        verbose_name=_("Fan Art"),
        help_text=_("Enter image URL of resolution width 780"),
        blank=True,
        null=True)
    field_history = FieldHistoryTracker(
        ['genre_id', 'genre_name', 'poster_path'])

    def get_reference_id(self):
        _id = self.id
        _app_name = os.path.basename(os.path.dirname(__file__))
        _model_name = self.__class__.__name__.lower()
        _url = reverse_lazy('admin:{}_{}_changelist'.format(
            _app_name, _model_name))
        _href = "<a href='{0}{1}/change/'>{1}</a>".format(_url, _id)
        return _href

    def __str__(self):
        return "{}".format(self.genre_name)

    class Meta:
        verbose_name = _("Genre")
Ejemplo n.º 6
0
class SchoolYear(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    label = models.CharField("Label", max_length=50)
    start = models.DateField("Start")
    end = models.DateField("End")
    open = models.BooleanField("Open for Applications?", default=False)

    field_history = FieldHistoryTracker(["open"])
Ejemplo n.º 7
0
class PizzaOrder(models.Model):
    STATUS_CHOICES = (
        ('ORDERED', 'Ordered'),
        ('COOKING', 'Cooking'),
        ('COMPLETE', 'Complete'),
    )
    status = models.CharField(max_length=64, choices=STATUS_CHOICES)

    field_history = FieldHistoryTracker(['status'])
Ejemplo n.º 8
0
class Evidence(models.Model):
    """A piece of evidence for an ACH matrix."""

    board = models.ForeignKey(Board, on_delete=models.CASCADE)

    creator = models.ForeignKey(
        User,
        null=True,
        on_delete=models.SET_NULL,
    )

    evidence_desc = models.CharField(
        "evidence description",
        max_length=EVIDENCE_MAX_LENGTH,
        help_text=
        _("A short summary of the evidence. Use the event date field for capturing the date"
          ),
    )

    event_date = models.DateField(
        "evidence event date",
        # Don't require evidence date because some evidence doesn't have a fixed start date. However, it can be useful
        # to sort evidence by when it occurred, therefore in the future we might want to allow setting a year, month,
        # or complete date
        null=True,
        blank=True,
        help_text=_("The date the event occurred or started"),
    )

    submit_date = models.DateTimeField("date added", auto_now_add=True)

    removed = models.BooleanField(default=False)

    field_history = FieldHistoryTracker(
        ["evidence_desc", "event_date", "removed"])

    objects = RemovableModelManager()
    all_objects = models.Manager()

    class Meta:  # pylint: disable=too-few-public-methods
        """Evidence Model meta options.

        For more information, please see:
            https://docs.djangoproject.com/en/1.10/topics/db/models/#meta-options
        """

        verbose_name_plural = _("evidence")

    def __str__(self):
        """Return a human-readable representation of the evidence."""
        return self.evidence_desc

    def get_canonical_url(self):
        """Return the canonical URL for view evidence details."""
        return reverse("openach:evidence_detail", args=(self.id, ))
Ejemplo n.º 9
0
class Person(models.Model):
    name = models.CharField(max_length=255)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL,
                                   null=True,
                                   blank=True)

    field_history = FieldHistoryTracker(['name'])

    @property
    def _field_history_user(self):
        return self.created_by
Ejemplo n.º 10
0
class Human(models.Model):
    age = models.IntegerField(blank=True, null=True)
    is_female = models.BooleanField(default=True)
    body_temp = models.DecimalField(max_digits=15,
                                    decimal_places=2,
                                    blank=True,
                                    null=True)
    birth_date = models.DateField(blank=True, null=True)

    field_history = FieldHistoryTracker(
        ['age', 'is_female', 'body_temp', 'birth_date'])
Ejemplo n.º 11
0
class Action(models.Model):
    STARTED_APPLICATION = 0
    COMPLETED_APPLICATION = 1
    APPLICATION_REVIEWED = 2
    SCHEDULED_TOUR = 3
    COMPLETED_TOUR = 4
    TOUR_FOLLOWUP = 5
    PREPARED_CONTRACT = 6
    SENT_CONTRACT = 7
    RETURNED_CONTRACT = 8
    EMAIL = 90
    PHONE_CALL = 91
    MAILING = 92
    OTHER = 99
    ACTION_CHOICES = (
        (STARTED_APPLICATION, "Started Application"),
        (COMPLETED_APPLICATION, "Completed Application"),
        (APPLICATION_REVIEWED, "Reviewed Application"),
        (SCHEDULED_TOUR, "Tour Scheduled"),
        (COMPLETED_TOUR, "Tour Completed"),
        (TOUR_FOLLOWUP, "Tour Follow-Up"),
        (PREPARED_CONTRACT, "Prepared Contract"),
        (SENT_CONTRACT, "Sent Contract"),
        (RETURNED_CONTRACT, "Contract Returned"),
        (EMAIL, "Email Communication"),
        (PHONE_CALL, "Phone Call"),
        (MAILING, "Physical Mailing"),
        (OTHER, "Other"),
    )

    WAITING_ON = -1
    TODO = 0
    COMPLETE = 1
    STATUS_CHOICES = ((WAITING_ON, "Waiting"), (TODO, "To-do"), (COMPLETE,
                                                                 "Completed"))

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    type = models.IntegerField("Type of Action",
                               choices=ACTION_CHOICES,
                               default=OTHER)
    date = models.DateTimeField("Date/Time")
    description = models.CharField("Notes", max_length=254, blank=True)
    status = models.IntegerField("Status",
                                 choices=STATUS_CHOICES,
                                 default=COMPLETE)
    # user = models.ForeignKey(get_user_model(), on_delete=models.PROTECT, null=True)

    field_history = FieldHistoryTracker(["description"])
Ejemplo n.º 12
0
class Board(models.Model):
    """An ACH matrix with hypotheses, evidence, and evaluations."""

    board_title = models.CharField(max_length=BOARD_TITLE_MAX_LENGTH)
    board_slug = models.SlugField(null=True,
                                  allow_unicode=False,
                                  max_length=SLUG_MAX_LENGTH)
    board_desc = models.CharField('board description',
                                  max_length=BOARD_DESC_MAX_LENGTH)
    creator = models.ForeignKey(User, null=True)
    pub_date = models.DateTimeField('date published')
    removed = models.BooleanField(default=False)
    field_history = FieldHistoryTracker(
        ['board_title', 'board_desc', 'removed'])

    objects = RemovableModelManager()
    all_objects = models.Manager()

    def __str__(self):
        """Return a human-readable representation of the board."""
        return self.board_title

    def was_published_recently(self):
        """Return True iff the Board was created recently."""
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now

    def get_absolute_url(self):
        """Return the absolute URL for viewing the board details, including the slug."""
        if self.board_slug:
            try:
                return reverse('openach:detail_slug',
                               args=(
                                   self.id,
                                   self.board_slug,
                               ))
            except NoReverseMatch:
                logger.warning("Malformed SLUG for reverse URL match: %s",
                               self.board_slug)
                return reverse('openach:detail', args=(self.id, ))
        else:
            return self.get_canonical_url()

    def get_canonical_url(self):
        """Return the canonical URL for view board details, excluding the slug."""
        return reverse('openach:detail', args=(self.id, ))
Ejemplo n.º 13
0
class Team(models.Model):
    """Analysis team."""

    objects = TeamModelManager()

    creator = models.ForeignKey(
        User,
        null=True,
        on_delete=models.SET_NULL,
        related_name='+'
    )

    owner = models.ForeignKey(
        User,
        null=True,
        on_delete=models.SET_NULL,
        related_name='+',
    )

    name = models.CharField(max_length=64, unique=True)

    description = models.TextField(blank=True)

    url = models.URLField(null=True, blank=True)

    members = models.ManyToManyField(User, blank=True, editable=False)

    public = models.BooleanField(
        default=True,
        help_text=_('Whether or not the team is visible to non-members')
    )

    invitation_required = models.BooleanField(default=True)

    create_timestamp = models.DateTimeField(auto_now_add=True)

    field_history = FieldHistoryTracker(['name', 'description', 'url', 'public', 'invitation_required'])

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('openach:view_team', args=(self.id,))
Ejemplo n.º 14
0
class Peticion_Impresiones_Color(models.Model):
    nombre_Emp = models.CharField(max_length=30, verbose_name="Nombre")
    ApellidoP_Emp = models.CharField(max_length=30,
                                     verbose_name="Apellido Paterno")
    ApellidoM_Emp = models.CharField(max_length=30,
                                     verbose_name="Apellido Materno")
    Clave = models.ManyToManyField(Clave_Impresion)
    saldo = models.PositiveIntegerField()
    Fecha = models.DateField(default=datetime.date.today, verbose_name='Fecha')
    Status_choice = (
        ('Solicitado', 'Solicitado'),
        ('En proceso', 'En proceso'),
        ('Atendida', 'Atendida'),
    )
    Status = models.CharField(max_length=15,
                              choices=Status_choice,
                              default='Solicitado')
    field_history = FieldHistoryTracker(['Status'])

    class Meta:
        verbose_name = "Petición de impresiones"
        verbose_name_plural = "Peticiones de impresiones"

    def save(self, *args, **kwargs):
        if self.Status == 'Solicitado':
            account_sid = os.environ.get('AC6882f5c66eedb6b8a6e733b24df48618')
            auth_token = os.environ.get('70a0acdeae855e8f4843b735c8a48de2')
            client = Client('AC6882f5c66eedb6b8a6e733b24df48618',
                            '70a0acdeae855e8f4843b735c8a48de2')
            message = client.messages.create(
                body='Se ha enviado una solicitud de computadoras',
                from_='+12059648210',
                to='+525511546778',
            )
            print(message.sid)
        return super().save(*args, **kwargs)
Ejemplo n.º 15
0
class Owner(models.Model):
    name = models.CharField(max_length=255)
    pet = models.ForeignKey(Pet, blank=True, null=True)

    field_history = FieldHistoryTracker(['pet'])
Ejemplo n.º 16
0
class Board(models.Model):
    """An ACH matrix with hypotheses, evidence, and evaluations."""

    class Meta:  # pylint: disable=too-few-public-methods
        """Board Model meta options.

        For more information, please see:
          https://docs.djangoproject.com/en/1.10/topics/db/models/#meta-options
        """

        ordering = ('-pub_date', )

    board_title = models.CharField(
        max_length=BOARD_TITLE_MAX_LENGTH,
        db_index=True,
        help_text=_('The board title. Typically phrased as a question asking about what happened in the past, '
                    'what is happening currently, or what will happen in the future'),
    )

    board_slug = models.SlugField(
        null=True,
        allow_unicode=False,
        max_length=SLUG_MAX_LENGTH,
        editable=False
    )

    board_desc = models.CharField(
        'board description',
        max_length=BOARD_DESC_MAX_LENGTH,
        db_index=True,
        help_text=_('A description providing context around the topic. Helps to clarify which hypotheses '
                    'and evidence are relevant')
    )

    creator = models.ForeignKey(User, null=True)
    pub_date = models.DateTimeField('date published')
    removed = models.BooleanField(default=False)
    field_history = FieldHistoryTracker(['board_title', 'board_desc', 'removed'])

    objects = BoardModelManager()
    all_objects = models.Manager()

    def __str__(self):
        """Return a human-readable representation of the board."""
        return self.board_title

    def save(self, *args, **kwargs):
        """Update slug on save."""
        self.board_slug = slugify(self.board_title, max_length=SLUG_MAX_LENGTH)
        return super().save(*args, **kwargs)

    def was_published_recently(self):
        """Return True iff the Board was created recently."""
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now

    def get_absolute_url(self):
        """Return the absolute URL for viewing the board details, including the slug."""
        if self.board_slug:
            try:
                return reverse('openach:detail_slug', args=(self.id, self.board_slug,))
            except NoReverseMatch:
                logger.warning('Malformed SLUG for reverse URL match: %s', self.board_slug)
                return reverse('openach:detail', args=(self.id,))
        else:
            return self.get_canonical_url()

    def get_canonical_url(self):
        """Return the canonical URL for view board details, excluding the slug."""
        return reverse('openach:detail', args=(self.id,))

    def is_collaborator(self, user):
        """Return True if the user is a collaborator on the board.

        Checks for direct collaboration and collaboration via a team.
        """
        return self.permissions.collaborators.filter(pk=user.id).exists() or \
               self.permissions.teams.filter(pk__in=user.team_set.values_list('id', flat=True)).exists()

    def collaborator_ids(self):
        """Return set of collaborator ids for the board."""
        direct = set(self.permissions.collaborators.values_list('id', flat=True))
        team = set(Team.objects.filter(pk__in=self.permissions.teams.all()).values_list('members__id', flat=True).distinct())
        return direct | team

    def can_read(self, user):
        """Return True if user can read the board."""
        if user.is_staff or user == self.creator:
            # avoid fetching permissions
            return True
        else:
            read = self.permissions.read_board
            return read == AuthLevels.anyone.key or \
                (user.is_authenticated and read == AuthLevels.registered.key) or \
                (read == AuthLevels.collaborators and self.is_collaborator(user))

    def has_collaborators(self):
        """Return True if the board has collaborators set."""
        return self.permissions.collaborators.exists() or self.permissions.teams.exists()

    def has_follower(self, user):
        """Return true iff user follows this board."""
        return self.followers.filter(user=user).exists()
Ejemplo n.º 17
0
class UserContributionModel(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    contribution = models.PositiveSmallIntegerField(default=0)
    workCompleted = models.PositiveSmallIntegerField(
        default=0)  # Specific for NGO
    field_history = FieldHistoryTracker(['contribution'])
Ejemplo n.º 18
0
class Job(CommonFieldsMixin):
    """Job post associated with project."""

    related_name = 'jobs'
    related_query_name = 'job'

    created_by = models.ForeignKey(User,
                                   db_index=True,
                                   related_name='created_jobs',
                                   related_query_name='created_job',
                                   on_delete=models.CASCADE)
    group = models.ForeignKey(Group,
                              null=True,
                              blank=True,
                              related_name=related_name,
                              related_query_name=related_query_name)

    applicants = models.ManyToManyField(User,
                                        through='application.Application',
                                        related_name=related_name,
                                        related_query_name=related_query_name)

    role_position = models.CharField(
        null=True,
        blank=True,
        max_length=255,
        help_text=
        'For eg. lead character, supporting character, background dancer etc.')
    ages = IntegerRangeField(null=True,
                             blank=True,
                             help_text='Age range required for this role.')
    required_gender = models.CharField(max_length=2,
                                       choices=choices.GENDER_CHOICES,
                                       default=choices.NOT_SPECIFIED)
    required_tokens = models.IntegerField(
        default=5,
        help_text='How much tokens user needs to have to apply to this job.')
    location = models.ForeignKey(
        City,
        null=True,
        blank=True,
        help_text="Location of user's project experience.")
    required_information_to_apply = hstore.DictionaryField(null=True,
                                                           blank=True)
    reason_for_rejection = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        help_text='Reason why the job was rejected/unapproved by stageroute.')
    submission_deadline = models.DateField(
        null=True, blank=True, help_text='Date for the job deadline.')

    status = models.CharField(max_length=2,
                              choices=choices.JOB_STATE_CHOICES,
                              default=choices.PENDING_APPROVAL)
    number_of_vacancies = models.IntegerField(
        default=1, help_text='How many positions are open for this job.')
    budgets = IntegerRangeField(
        null=True,
        blank=True,
        help_text='budget range amount to be spent on the job.')
    featured = models.BooleanField(default=False, help_text='Is job featured.')
    skin_type = models.CharField(max_length=50,
                                 null=True,
                                 blank=True,
                                 default=choices.DOES_NOT_MATTER,
                                 choices=choices.SKIN_TYPE_CHOICES,
                                 help_text='Preferred skin type.')
    hair_type = models.CharField(max_length=50,
                                 null=True,
                                 blank=True,
                                 default=choices.DOES_NOT_MATTER,
                                 choices=choices.HAIR_TYPE_CHOICES,
                                 help_text='Preferred hair type.')
    eye_color = models.CharField(max_length=50,
                                 default=choices.DOES_NOT_MATTER,
                                 null=True,
                                 blank=True,
                                 choices=choices.EYE_COLOR_CHOICES,
                                 help_text='Peferred eye color.')
    hair_color = models.CharField(max_length=50,
                                  default=choices.DOES_NOT_MATTER,
                                  null=True,
                                  blank=True,
                                  choices=choices.HAIR_COLOR_CHOICES,
                                  help_text='Peferred eye color.')
    hair_style = models.CharField(max_length=50,
                                  default=choices.DOES_NOT_MATTER,
                                  null=True,
                                  blank=True,
                                  choices=choices.HAIR_STYLE_CHOICES,
                                  help_text='Peferred eye color.')
    heights = FloatRangeField(null=True,
                              blank=True,
                              help_text='Range of height required.')
    body_type = models.CharField(max_length=50,
                                 null=True,
                                 blank=True,
                                 default=choices.DOES_NOT_MATTER,
                                 choices=choices.BODY_TYPES)
    language = models.CharField(max_length=50,
                                null=True,
                                blank=True,
                                default=choices.DOES_NOT_MATTER,
                                choices=choices.LANGUAGE_CHOICES,
                                help_text='Preferred languages.')

    job_type = models.CharField(max_length=50,
                                null=True,
                                blank=True,
                                choices=choices.JOB_TYPE_CHOICES,
                                help_text='Type of job.')
    auditions_per_day = models.IntegerField(
        null=True,
        blank=True,
        help_text='Number of auditions to do per day for this job.')
    audition_range = DateRangeField(null=True,
                                    blank=True,
                                    help_text='Audition range')
    job_owner_email = models.EmailField(
        null=True,
        blank=True,
        help_text='Should be valid email, e.g. [email protected]',
    )
    job_owner_phone = models.CharField(max_length=10,
                                       null=True,
                                       blank=True,
                                       db_index=True,
                                       help_text="User's phone number.")
    notes = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        help_text="Useful for job posters. A quick note they can refere later."
    )
    field_history = FieldHistoryTracker(['status'])
    related_query_name = 'jobs'

    images = GenericRelation(Image, related_query_name=related_query_name)
    videos = GenericRelation(Video, related_query_name=related_query_name)
    audios = GenericRelation(Audio, related_query_name=related_query_name)
    objects = hstore.HStoreManager()

    def __unicode__(self):
        """unicode."""
        return self.title
Ejemplo n.º 19
0
class Board(models.Model):
    """An ACH matrix with hypotheses, evidence, and evaluations."""

    board_title = models.CharField(
        max_length=BOARD_TITLE_MAX_LENGTH,
        db_index=True,
        help_text=_(
            'The board title. Typically phrased as a question asking about what happened in the past, '
            'what is happening currently, or what will happen in the future'),
    )

    board_slug = models.SlugField(null=True,
                                  allow_unicode=False,
                                  max_length=SLUG_MAX_LENGTH,
                                  editable=False)

    board_desc = models.CharField(
        'board description',
        max_length=BOARD_DESC_MAX_LENGTH,
        db_index=True,
        help_text=_(
            'A description providing context around the topic. Helps to clarify which hypotheses '
            'and evidence are relevant'))

    creator = models.ForeignKey(User, null=True)
    pub_date = models.DateTimeField('date published')
    removed = models.BooleanField(default=False)
    field_history = FieldHistoryTracker(
        ['board_title', 'board_desc', 'removed'])

    objects = RemovableModelManager()
    all_objects = models.Manager()

    def __str__(self):
        """Return a human-readable representation of the board."""
        return self.board_title

    def save(self, *args, **kwargs):
        """Update slug on save."""
        self.board_slug = slugify(self.board_title, max_length=SLUG_MAX_LENGTH)
        return super().save(*args, **kwargs)

    def was_published_recently(self):
        """Return True iff the Board was created recently."""
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now

    def get_absolute_url(self):
        """Return the absolute URL for viewing the board details, including the slug."""
        if self.board_slug:
            try:
                return reverse('openach:detail_slug',
                               args=(
                                   self.id,
                                   self.board_slug,
                               ))
            except NoReverseMatch:
                logger.warning('Malformed SLUG for reverse URL match: %s',
                               self.board_slug)
                return reverse('openach:detail', args=(self.id, ))
        else:
            return self.get_canonical_url()

    def get_canonical_url(self):
        """Return the canonical URL for view board details, excluding the slug."""
        return reverse('openach:detail', args=(self.id, ))
Ejemplo n.º 20
0
class Player(models.Model):
    name = models.TextField(default='', max_length=20)
    rating = models.IntegerField(default=1500)
    league = models.ForeignKey(League, related_name='players', default=None)
    rating_history = FieldHistoryTracker(['rating'])
Ejemplo n.º 21
0
class Computadora(models.Model):
    no_Serie_Co = models.CharField(primary_key=True,
                                   max_length=30,
                                   verbose_name="No. de serie")
    nombre_Co = models.CharField(max_length=30, verbose_name="Nombre")
    marca = models.CharField(max_length=10)
    modelo_com = models.CharField(max_length=30, verbose_name="Modelo")
    tipo_Choices = (
        (1, 'pcescritorio'),
        (2, 'laptop'),
    )
    tipo_com = models.IntegerField(choices=tipo_Choices, default=1)
    Status_Choice = (
        ("disponible", "disponible"),
        ("servicio", "servicio"),
        ("reparacion", "reparación"),
        ("destruccion", "destruccion"),
    )
    Status = models.CharField(max_length=30, choices=Status_Choice)
    Ram_Choice = (
        ('2GB', '2GB'),
        ('4GB', '4GB'),
        ('8GB', '8GB'),
        ('16GB', '16GB'),
    )
    Ram = models.CharField(max_length=5, choices=Ram_Choice, null=True)
    Dd_Choice = (
        ('500Gb', '500Gb'),
        ('1TB', '1TB'),
        ('1.5TB', '1.5TB'),
        ('2TB', '2TB'),
        ('2.5TB', '2.5TB'),
        ('3TB', '3TB'),
    )
    Disco_Duro = models.CharField(max_length=6,
                                  choices=Dd_Choice,
                                  verbose_name='Disco Duro',
                                  null=True)
    Procesador = models.CharField(max_length=20, null=True)
    Ano = models.IntegerField(verbose_name="Año", null=True)
    qr_code = models.ImageField(upload_to='qr_codes', blank=True, null=True)
    field_history = FieldHistoryTracker(['Status'])

    def __str__(self):
        return self.no_Serie_Co

    def __unicode__(self):
        return self.nombre_Co

    def save(self, *args, **kwargs):
        dicttionary = {
            "Num.Serie": self.no_Serie_Co,
            "Nombre": self.nombre_Co,
            "Marca": self.marca,
            "Modelo": self.modelo_com,
            "Disco Duro": self.Disco_Duro,
            "Procesador": self.Procesador,
            "Ram": self.Ram
        }
        qrcode_img = qrcode.make(dicttionary)
        canvas = Image.new('RGB', (590, 590), 'white')
        draw = ImageDraw.Draw(canvas)
        canvas.paste(qrcode_img)
        fnombre_Co = f'qr_code-{dicttionary}.png'
        buffer = BytesIO()
        canvas.save(buffer, 'PNG')
        self.qr_code.save(fnombre_Co, File(buffer), save=False)
        canvas.close()
        super(Computadora, self).save(*args, **kwargs)
Ejemplo n.º 22
0
class Solicitud_Equipo(models.Model):
    nombre_Emp = models.CharField(max_length=30, verbose_name="Nombre")
    ApellidoP_Emp = models.CharField(max_length=30,
                                     verbose_name="Apellido Paterno")
    ApellidoM_Emp = models.CharField(max_length=30,
                                     verbose_name="Apellido Materno")
    Area = models.ForeignKey(Area, on_delete=models.CASCADE)
    Proyecto = models.ForeignKey(Proyecto, on_delete=models.CASCADE)
    tipo_Choice = (
        ('pce', 'pcescritorio'),
        ('lap', 'lap'),
    )
    tipo_com = models.CharField(max_length=3,
                                choices=tipo_Choice,
                                verbose_name="Tipo de computadora")
    Office_Choice = (
        ("O365", "Office365"),
        ("Win7", "Windows7"),
    )
    Office = models.CharField(max_length=4, choices=Office_Choice)
    App_Choices = (
        ('ERP', 'SAP 7.4'),
        ('Costos', 'Costos unitarios'),
        ('Autocad', 'Autocad 2018'),
        ('Adobe reader', 'Adobe'),
        ('VPN', 'Cliente VPN'),
        ('DoPDF', 'DoPDF'),
        ('7-zip', '7-zip'),
        ('Control', 'Software de control Proyecto'),
        ('Diagramación', 'Software de diagramación'),
    )
    teclado_Choices = (
        ('aplica', 'aplica'),
        ('no aplica', 'no aplica'),
    )
    teclado = models.CharField(max_length=15, choices=teclado_Choices)
    monitor_Choices = (
        ('aplica', 'aplica'),
        ('no aplica', 'no aplica'),
    )
    monitor = models.CharField(max_length=15, choices=monitor_Choices)
    Aplicaciones = models.CharField(max_length=100, blank=True, null=True)
    Equipo_Adicional_choices = (
        ('IP', 'Telefonia IP'),
        ('Movil', 'Celular'),
        ('Radio', 'Radio'),
        ('N/A', 'No aplica'),
    )
    #Equipo_Adicional = SelectMultipleField(max_length=20,choices=Equipo_Adicional_choices)
    Status_choice = (
        ('Solicitado', 'Solicitado'),
        ('En proceso', 'En proceso'),
        ('Atendida', 'Atendida'),
    )
    Status = models.CharField(max_length=15, choices=Status_choice)
    Fecha_inicio = models.DateField(default=datetime.date.today,
                                    verbose_name='Fecha de entrega de equipo')
    field_history = FieldHistoryTracker(['Status'])

    class Meta:
        verbose_name = 'Solicitud de Equipo'
        verbose_name_plural = 'Solicitud de Equipo'

    def save(self, *args, **kwargs):
        if self.Aplicaciones:
            self.Aplicaciones = eval(self.Aplicaciones)
        if self.Status == 'Solicitado':
            account_sid = os.environ.get('AC6882f5c66eedb6b8a6e733b24df48618')
            auth_token = os.environ.get('70a0acdeae855e8f4843b735c8a48de2')
            client = Client('AC6882f5c66eedb6b8a6e733b24df48618',
                            '70a0acdeae855e8f4843b735c8a48de2')
            message = client.messages.create(
                body='Se ha enviado una solicitud de computadoras',
                from_='+12059648210',
                to='+525511546778',
            )
            print(message.sid)
        return super().save(*args, **kwargs)
Ejemplo n.º 23
0
class Board(models.Model):
    """An ACH matrix with hypotheses, evidence, and evaluations."""

    class Meta:  # pylint: disable=too-few-public-methods
        """Board Model meta options.

        For more information, please see:
          https://docs.djangoproject.com/en/1.10/topics/db/models/#meta-options
        """

        ordering = ("-pub_date",)

    validate_special = RegexValidator(
        r"^((?![!@#^*~`|<>{}+=\[\]]).)*$", "No special characters allowed."
    )
    # When user clicks 'Create Board', validator stops any instance of these characters: !@#^*~`|<>{}+=[]

    board_title = models.CharField(
        max_length=BOARD_TITLE_MAX_LENGTH,
        db_index=True,
        help_text=_(
            "The board title. Typically phrased as a question asking about what happened in the past, "
            "what is happening currently, or what will happen in the future"
        ),
        validators=[validate_special],
    )

    board_slug = models.SlugField(
        null=True, allow_unicode=False, max_length=SLUG_MAX_LENGTH, editable=False
    )

    board_desc = models.CharField(
        "board description",
        max_length=BOARD_DESC_MAX_LENGTH,
        db_index=True,
        help_text=_(
            "A description providing context around the topic. Helps to clarify which hypotheses "
            "and evidence are relevant"
        ),
    )

    creator = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)

    pub_date = models.DateTimeField("date published")

    removed = models.BooleanField(default=False)

    field_history = FieldHistoryTracker(["board_title", "board_desc", "removed"])

    objects = BoardModelManager()

    all_objects = models.Manager()

    def __str__(self):
        """Return a human-readable representation of the board."""
        return self.board_title

    def save(self, *args, **kwargs):
        """Update slug on save."""
        self.board_slug = slugify(self.board_title, max_length=SLUG_MAX_LENGTH)
        return super().save(*args, **kwargs)

    def was_published_recently(self):
        """Return True iff the Board was created recently."""
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now

    def get_absolute_url(self):
        """Return the absolute URL for viewing the board details, including the slug."""
        if self.board_slug:
            try:
                return reverse("openach:detail_slug", args=(self.id, self.board_slug,))
            except NoReverseMatch:
                logger.warning(
                    "Malformed SLUG for reverse URL match: %s", self.board_slug
                )
                return reverse("openach:detail", args=(self.id,))
        else:
            return self.get_canonical_url()

    def get_canonical_url(self):
        """Return the canonical URL for view board details, excluding the slug."""
        return reverse("openach:detail", args=(self.id,))

    def is_collaborator(self, user):
        """Return True if the user is a collaborator on the board.

        Checks for direct collaboration and collaboration via a team.
        """
        return (
            self.permissions.collaborators.filter(pk=user.id).exists()
            or self.permissions.teams.filter(members__pk=user.id).exists()
        )

    def collaborator_ids(self):
        """Return set of collaborator ids for the board."""
        direct = set(self.permissions.collaborators.values_list("id", flat=True))
        team = set(
            Team.objects.filter(pk__in=self.permissions.teams.all())
            .values_list("members__id", flat=True)
            .distinct()
        )
        return direct | team

    def can_read(self, user):
        """Return True if user can read the board."""
        return "read_board" in self.permissions.for_user(user)

    def has_collaborators(self):
        """Return True if the board has collaborators set."""
        return (
            self.permissions.collaborators.exists() or self.permissions.teams.exists()
        )

    def has_follower(self, user):
        """Return true iff user follows this board."""
        return self.followers.filter(user=user).exists()
Ejemplo n.º 24
0
class Ordenes_Servicio(models.Model):
    nombre_Emp = models.CharField(max_length=30, verbose_name="Nombre")
    ApellidoP_Emp = models.CharField(max_length=30,
                                     verbose_name="Apellido Paterno")
    ApellidoM_Emp = models.CharField(max_length=30,
                                     verbose_name="Apellido Materno")
    Proyecto = models.ForeignKey(Proyecto, on_delete=models.CASCADE)
    Area = models.ForeignKey(Area, on_delete=models.CASCADE)
    Atencion = models.OneToOneField(User,
                                    on_delete=models.CASCADE,
                                    null=True,
                                    blank=True,
                                    verbose_name="Ingeniero Responsable")
    clasificacion_equipo_revisar_choices = (
        ("CPU", "CPU"),
        ("LAPTOP", "LAPTOP"),
        ("TelefoniaIP", "TelefoníaIP"),
        ("Celuslar", "Celular"),
    )
    clasificacion_equipo = models.CharField(
        choices=clasificacion_equipo_revisar_choices,
        null=True,
        blank=True,
        max_length=15,
        verbose_name="Equipo",
    )
    tipo_atencion_choices = (
        ("Telefónica", "Telefónica"),
        ("Remota", "Remota"),
        ("Presencial", "Presencial"),
    )
    tipo_atencion = models.CharField(choices=tipo_atencion_choices,
                                     null=True,
                                     blank=True,
                                     max_length=15,
                                     verbose_name="Tipo de atención")
    cuestionario_choices = (("si", "si"), ("no", "no"), ("no aplica",
                                                         "no aplica"))
    dano_fisico = models.CharField(
        choices=cuestionario_choices,
        max_length=10,
        null=True,
        blank=True,
        help_text="El equipo presenta daño por uso o descuido",
        verbose_name="Daño físico")
    retirar = models.CharField(choices=cuestionario_choices,
                               max_length=10,
                               null=True,
                               blank=True,
                               help_text="¿Se retiró el equipo?",
                               verbose_name="Retirar equipo")
    codigo_error = models.CharField(choices=cuestionario_choices,
                                    max_length=10,
                                    null=True,
                                    blank=True,
                                    help_text="¿Presenta código de error?")
    solucion = models.CharField(choices=cuestionario_choices,
                                max_length=10,
                                help_text="¿Se soluciono la incidencia?",
                                verbose_name="Solucion")
    fecha_inicidencia = models.DateTimeField(auto_now_add=True)
    fecha_resolucion = models.DateField(
        null=True,
        blank=True,
    )
    reporte_usuario = models.TextField(
        blank=True,
        null=True,
        help_text="Indique detalladamente su problema",
        verbose_name="Descripción de la incidencia")
    reporte_resolucion = models.TextField(
        blank=True,
        null=True,
        help_text="Indique detalladamente la resolución del problema",
        verbose_name="Descripción de la solución")
    observaciones = models.TextField(verbose_name="Obsevaciones",
                                     null=True,
                                     blank=True)
    Status_choice = (
        ('Solicitado', 'Solicitado'),
        ('En proceso', 'En proceso'),
        ('Atendida', 'Atendida'),
    )
    Status = models.CharField(max_length=15,
                              choices=Status_choice,
                              default='Solicitado',
                              null=True,
                              blank=True)
    field_history = FieldHistoryTracker(['Status'])

    class Meta:
        verbose_name = "Orden de servicio"
        verbose_name_plural = "Ordenes de servicio"

    def save(self, *args, **kwargs):
        if self.Status == 'Solicitado':
            account_sid = os.environ.get('AC6882f5c66eedb6b8a6e733b24df48618')
            auth_token = os.environ.get('70a0acdeae855e8f4843b735c8a48de2')
            client = Client('AC6882f5c66eedb6b8a6e733b24df48618',
                            '70a0acdeae855e8f4843b735c8a48de2')
            message = client.messages.create(
                body='Se ha enviado una orden de servicio',
                from_='+12059648210',
                to='+525511546778',
            )
            print(message.sid)
        return super().save(*args, **kwargs)
Ejemplo n.º 25
0
class Company(TimeStampedModel):
    company_type = models.CharField(max_length=15,
                                    choices=choices.COMPANY_TYPES,
                                    default=company_types.COMPANIES_HOUSE)
    summary = models.CharField(
        max_length=250,
        blank=True,
        default='',
        validators=[no_html],
    )
    description = models.TextField(
        blank=True,
        default='',
        validators=[no_html],
    )
    employees = models.CharField(
        max_length=20,
        choices=choices.EMPLOYEES,
        blank=True,
        default='',
    )
    export_destinations = JSONField(
        blank=True,
        default=[],
        help_text=("Of the countries the project have prioritised,"
                   "which does the company want to export to (whitelisted)"))
    export_destinations_other = models.CharField(
        max_length=1000,
        blank=True,
        default='',
        help_text=("Of the countries the project have not prioritised,"
                   "which does the company want to export to (free text)."),
        validators=[no_html],
    )
    expertise_industries = JSONField(
        blank=True,
        default=[],
        help_text=("The industries that this company has expertise in,"
                   "this allows searching and filtering for this selection"))
    expertise_regions = JSONField(
        blank=True,
        default=[],
        help_text="The regions that this company has expertise in.")
    expertise_countries = JSONField(
        blank=True,
        default=[],
        help_text="The countries that this company has expertise in.")
    expertise_languages = JSONField(
        blank=True,
        default=[],
        help_text="The languages that this company has expertise in.")
    expertise_products_services = JSONField(
        blank=True,
        default={},
        help_text="The products and services the company has expertise in.")
    has_exported_before = models.NullBooleanField()
    is_exporting_goods = models.BooleanField(default=False)
    is_exporting_services = models.BooleanField(default=False)
    keywords = models.TextField(
        blank=True,
        default='',
        validators=[no_html],
    )
    logo = models.ImageField(
        upload_to=helpers.path_and_rename_logos,
        default='',
        blank=True,
    )
    name = models.CharField(
        max_length=255,
        validators=[no_html],
    )
    number = models.CharField(
        help_text=(
            'For companies registered in companies house this is their '
            'companies house number. For sole trader this is any randomly '
            'generated string.'),
        max_length=8,
        validators=[shared_validators.company_number, no_html],
        unique=True,
        null=True,
        blank=True,
    )
    sectors = JSONField(
        blank=True,
        default=[],
    )
    website = models.URLField(max_length=255, blank=True, default='')
    date_of_creation = models.DateField(
        blank=True,
        null=True,
    )
    is_published_investment_support_directory = models.BooleanField(
        default=False,
        help_text=(
            'Companies that have a published profile on investment support.'
            'completeness - they must have description or summary, be '
            'verified, and have an email address.'))

    is_published_find_a_supplier = models.BooleanField(
        default=False,
        help_text=('Companies that have a published profile on FAS '
                   'completeness - they must have description or summary, be '
                   'verified, and have an email address.'))
    date_published = models.DateField(null=True, blank=True)
    verification_code = models.CharField(
        _('verification code'),
        max_length=255,
        blank=True,
        default=helpers.generate_verification_code,
    )
    verified_with_preverified_enrolment = models.BooleanField(default=False)
    verified_with_code = models.BooleanField(default=False)
    verified_with_companies_house_oauth2 = models.BooleanField(default=False)
    is_verification_letter_sent = models.BooleanField(default=False)
    is_registration_letter_sent = models.BooleanField(default=False)
    date_registration_letter_sent = models.DateTimeField(null=True, blank=True)
    date_verification_letter_sent = models.DateTimeField(null=True, blank=True)
    # social links
    twitter_url = models.URLField(max_length=255, blank=True, default='')
    facebook_url = models.URLField(max_length=255, blank=True, default='')
    linkedin_url = models.URLField(
        max_length=255,
        blank=True,
        default='',
    )
    # contact details
    mobile_number = models.CharField(
        blank=True,
        default='',
        max_length=100,
    )
    postal_full_name = models.CharField(
        max_length=255,
        blank=True,
        default='',
        validators=[no_html],
    )
    address_line_1 = models.CharField(
        max_length=255,
        blank=True,
        default='',
        validators=[no_html],
    )
    address_line_2 = models.CharField(
        max_length=255,
        blank=True,
        default='',
        validators=[no_html],
    )
    locality = models.CharField(
        max_length=255,
        blank=True,
        default='',
        validators=[no_html],
    )
    country = models.CharField(
        max_length=255,
        blank=True,
        default='',
        validators=[no_html],
    )
    postal_code = models.CharField(
        max_length=255,
        blank=True,
        default='',
        validators=[no_html],
    )
    po_box = models.CharField(
        max_length=255,
        blank=True,
        default='',
        validators=[no_html],
    )
    email_address = models.EmailField(
        blank=True,
        default='',
    )
    email_full_name = models.CharField(
        max_length=200,
        blank=True,
        default='',
        validators=[no_html],
    )
    slug = models.SlugField()
    is_showcase_company = models.BooleanField(default=False)
    is_uk_isd_company = models.BooleanField(default=False)

    field_history = FieldHistoryTracker([
        'verified_with_preverified_enrolment',
        'verified_with_code',
        'verified_with_companies_house_oauth2',
    ])
    companies_house_company_status = models.CharField(
        max_length=255,
        blank=True,
        default='',
        validators=[no_html],
    )

    class Meta:
        verbose_name_plural = 'companies'

    def __str__(self):
        return self.name

    @property
    def is_publishable(self):
        has_contact = bool(self.email_address)
        has_synopsis = bool(self.description or self.summary)
        is_verified = self.is_verified
        return all([has_contact, has_synopsis, is_verified])

    @property
    def is_published(self):
        return any([
            self.is_published_investment_support_directory,
            self.is_published_find_a_supplier,
        ])

    @property
    def public_profile_url(self):
        return settings.FAS_COMPANY_PROFILE_URL.format(number=self.number)

    @property
    def is_verified(self):
        return any([
            self.verified_with_preverified_enrolment,
            self.verified_with_code,
            self.verified_with_companies_house_oauth2,
        ])

    def has_valid_address(self):
        required_address_fields = [
            'postal_full_name',
            'address_line_1',
            'postal_code',
        ]
        return all(getattr(self, field) for field in required_address_fields)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)[:50]
        return super().save(*args, **kwargs)