Example #1
0
class TemplateTask(models.Model):
    template = models.ForeignKey(Template)
    task = models.ForeignKey(Task)
    order = models.SmallIntegerField()
Example #2
0
class Review(models.Model):
    product = models.ForeignKey(Product)
    full_name = models.CharField(max_length=200)
    rating = models.IntegerField()
    comment = models.TextField(max_length=500)
Example #3
0
class Content(BaseModel):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    text = models.TextField(default='')

    class Meta:
        ordering = ['-created_at']
Example #4
0
class TaskItem(models.Model):

    class Meta:
        verbose_name = "задача"
        verbose_name_plural = "задачи"
        ordering = ['order_key']

    show = models.BooleanField(verbose_name="отображать", default=True)
    task = models.ForeignKey(Task, verbose_name='задача', related_name='topics')
    max_score = models.PositiveIntegerField(verbose_name='балл за решение', default=5)
    manual_check = models.BooleanField(verbose_name='ручная проверка', default=False)
    compiler_check = models.BooleanField(verbose_name='проверка автотестами', default=True)
    one_try = models.BooleanField(verbose_name='одна попытка', default=False)
    slug = SlugField(verbose_name="слаг", max_length=255, blank=True, null=True, for_fields=['topic'])

    number = models.PositiveIntegerField(verbose_name='порядковый номер', blank=True, null=True)
    order_key = OrderField(verbose_name='порядок', blank=True, null=True, for_fields=['topic'])
    topic = models.ForeignKey(Topic, verbose_name='тема', related_name='_taskitems')

    @property
    def lang(self):
        return self.topic.lang

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

    @property
    def numbered_title(self):
        data = self.get_cache_data()
        return '%s %s' % (data['number'], data['title'])

    @property
    def cache_key(self):
        return 'taskitem__%d' % self.id

    def get_data(self):
        return {
            'id': self.cache_key,
            'number': '%s.%s' % (self.topic.number, self.number),
            'title': self.title,
            'url': reverse('training:taskitem', kwargs={
                    'course': self.topic.course.slug,
                    'topic': self.topic.slug,
                    'taskitem': self.slug
                }
            )
        }

    def get_cache_data(self):
        json_data = cache.get(self.cache_key)
        if not json_data:
            data = self.get_data()
            cache.set(self.cache_key, json.dumps(data, ensure_ascii=False))
        else:
            data = json.loads(json_data)
        return data

    def get_breadcrumbs(self):
        return [
            {'title': 'Курсы', 'url': reverse('training:courses')},
            {'title': self.topic.course.title,   'url': self.topic.course.get_absolute_url()},
            {'title': self.topic.numbered_title, 'url': self.topic.get_absolute_url()},
        ]

    def get_absolute_url(self):
        return self.get_cache_data()['url']

    def __str__(self):
        return self.title
Example #5
0
class CablePath(BaseModel):
    """
    A CablePath instance represents the physical path from an origin to a destination, including all intermediate
    elements in the path. Every instance must specify an `origin`, whereas `destination` may be null (for paths which do
    not terminate on a PathEndpoint).

    `path` contains a list of nodes within the path, each represented by a tuple of (type, ID). The first element in the
    path must be a Cable instance, followed by a pair of pass-through ports. For example, consider the following
    topology:

                     1                              2                              3
        Interface A --- Front Port A | Rear Port A --- Rear Port B | Front Port B --- Interface B

    This path would be expressed as:

    CablePath(
        origin = Interface A
        destination = Interface B
        path = [Cable 1, Front Port A, Rear Port A, Cable 2, Rear Port B, Front Port B, Cable 3]
    )

    `is_active` is set to True only if 1) `destination` is not null, and 2) every Cable within the path has a status of
    "connected".
    """

    origin_type = models.ForeignKey(to=ContentType,
                                    on_delete=models.CASCADE,
                                    related_name="+")
    origin_id = models.UUIDField()
    origin = GenericForeignKey(ct_field="origin_type", fk_field="origin_id")
    destination_type = models.ForeignKey(
        to=ContentType,
        on_delete=models.CASCADE,
        related_name="+",
        blank=True,
        null=True,
    )
    destination_id = models.UUIDField(blank=True, null=True)
    destination = GenericForeignKey(ct_field="destination_type",
                                    fk_field="destination_id")
    path = JSONPathField()
    is_active = models.BooleanField(default=False)
    is_split = models.BooleanField(default=False)

    class Meta:
        unique_together = ("origin_type", "origin_id")

    def __str__(self):
        status = " (active)" if self.is_active else " (split)" if self.is_split else ""
        return f"Path #{self.pk}: {self.origin} to {self.destination} via {len(self.path)} nodes{status}"

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

        # Record a direct reference to this CablePath on its originating object
        model = self.origin._meta.model
        model.objects.filter(pk=self.origin.pk).update(_path=self.pk)

    @property
    def segment_count(self):
        total_length = 1 + len(self.path) + (1 if self.destination else 0)
        return int(total_length / 3)

    @classmethod
    def from_origin(cls, origin):
        """
        Create a new CablePath instance as traced from the given path origin.
        """
        if origin is None or origin.cable is None:
            return None

        # Import added here to avoid circular imports with Cable.
        from nautobot.circuits.models import CircuitTermination

        destination = None
        path = []
        position_stack = []
        is_active = True
        is_split = False

        node = origin
        visited_nodes = set()
        while node.cable is not None:
            if node.id in visited_nodes:
                raise ValidationError("a loop is detected in the path")
            visited_nodes.add(node.id)
            if node.cable.status != Cable.STATUS_CONNECTED:
                is_active = False

            # Follow the cable to its far-end termination
            path.append(object_to_path_node(node.cable))
            peer_termination = node.get_cable_peer()

            # Follow a FrontPort to its corresponding RearPort
            if isinstance(peer_termination, FrontPort):
                path.append(object_to_path_node(peer_termination))
                node = peer_termination.rear_port
                if node.positions > 1:
                    position_stack.append(peer_termination.rear_port_position)
                path.append(object_to_path_node(node))

            # Follow a RearPort to its corresponding FrontPort (if any)
            elif isinstance(peer_termination, RearPort):
                path.append(object_to_path_node(peer_termination))

                # Determine the peer FrontPort's position
                if peer_termination.positions == 1:
                    position = 1
                elif position_stack:
                    position = position_stack.pop()
                else:
                    # No position indicated: path has split, so we stop at the RearPort
                    is_split = True
                    break

                try:
                    node = FrontPort.objects.get(rear_port=peer_termination,
                                                 rear_port_position=position)
                    path.append(object_to_path_node(node))
                except ObjectDoesNotExist:
                    # No corresponding FrontPort found for the RearPort
                    break

            # Follow a Circuit Termination if there is a corresponding Circuit Termination
            # Side A and Side Z exist
            elif isinstance(peer_termination, CircuitTermination):
                node = peer_termination.get_peer_termination()
                # A Circuit Termination does not require a peer.
                if node is None:
                    destination = peer_termination
                    break
                path.append(object_to_path_node(peer_termination))
                path.append(object_to_path_node(node))

            # Anything else marks the end of the path
            else:
                destination = peer_termination
                break

        if destination is None:
            is_active = False

        return cls(
            origin=origin,
            destination=destination,
            path=path,
            is_active=is_active,
            is_split=is_split,
        )

    def get_path(self):
        """
        Return the path as a list of prefetched objects.
        """
        # Compile a list of IDs to prefetch for each type of model in the path
        to_prefetch = defaultdict(list)
        for node in self.path:
            ct_id, object_id = decompile_path_node(node)
            to_prefetch[ct_id].append(object_id)

        # Prefetch path objects using one query per model type. Prefetch related devices where appropriate.
        prefetched = {}
        for ct_id, object_ids in to_prefetch.items():
            model_class = ContentType.objects.get_for_id(ct_id).model_class()
            queryset = model_class.objects.filter(pk__in=object_ids)
            if hasattr(model_class, "device"):
                queryset = queryset.prefetch_related("device")
            prefetched[ct_id] = {obj.id: obj for obj in queryset}

        # Replicate the path using the prefetched objects.
        path = []
        for node in self.path:
            ct_id, object_id = decompile_path_node(node)
            path.append(prefetched[ct_id][object_id])

        return path

    def get_total_length(self):
        """
        Return the sum of the length of each cable in the path.
        """
        cable_ids = [
            # Starting from the first element, every third element in the path should be a Cable
            decompile_path_node(self.path[i])[1]
            for i in range(0, len(self.path), 3)
        ]
        return Cable.objects.filter(id__in=cable_ids).aggregate(
            total=Sum("_abs_length"))["total"]

    def get_split_nodes(self):
        """
        Return all available next segments in a split cable path.
        """
        rearport = path_node_to_object(self.path[-1])
        return FrontPort.objects.filter(rear_port=rearport)
Example #6
0
class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='AlternativeName',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=256)),
                ('language', models.CharField(max_length=100)),
                ('is_preferred', models.BooleanField(default=False)),
                ('is_short', models.BooleanField(default=False)),
                ('is_colloquial', models.BooleanField(default=False)),
            ],
        ),
        migrations.CreateModel(
            name='City',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=200, verbose_name=b'ascii name', db_index=True)),
                ('slug', models.CharField(max_length=200)),
                ('name_std', models.CharField(max_length=200, verbose_name=b'standard name', db_index=True)),
                ('location', django.contrib.gis.db.models.fields.PointField(srid=4326)),
                ('population', models.IntegerField()),
                ('elevation', models.IntegerField(null=True)),
                ('kind', models.CharField(max_length=10)),
                ('timezone', models.CharField(max_length=40)),
                ('alt_names', models.ManyToManyField(to='cities.AlternativeName')),
            ],
            options={
                'verbose_name_plural': 'cities',
            },
        ),
        migrations.CreateModel(
            name='Country',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=200, verbose_name=b'ascii name', db_index=True)),
                ('slug', models.CharField(max_length=200)),
                ('code', models.CharField(max_length=2, db_index=True)),
                ('code3', models.CharField(max_length=3, db_index=True)),
                ('population', models.IntegerField()),
                ('area', models.IntegerField(null=True)),
                ('currency', models.CharField(max_length=3, null=True)),
                ('currency_name', models.CharField(max_length=50, null=True)),
                ('languages', models.CharField(max_length=250, null=True)),
                ('phone', models.CharField(max_length=20)),
                ('continent', models.CharField(max_length=2)),
                ('tld', models.CharField(max_length=5)),
                ('capital', models.CharField(max_length=100)),
                ('alt_names', models.ManyToManyField(to='cities.AlternativeName')),
                ('neighbours', models.ManyToManyField(related_name='neighbours_rel_+', to='cities.Country')),
            ],
            options={
                'ordering': ['name'],
                'verbose_name_plural': 'countries',
            },
        ),
        migrations.CreateModel(
            name='District',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=200, verbose_name=b'ascii name', db_index=True)),
                ('slug', models.CharField(max_length=200)),
                ('name_std', models.CharField(max_length=200, verbose_name=b'standard name', db_index=True)),
                ('location', django.contrib.gis.db.models.fields.PointField(srid=4326)),
                ('population', models.IntegerField()),
                ('alt_names', models.ManyToManyField(to='cities.AlternativeName')),
                ('city', models.ForeignKey(to='cities.City')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='PostalCode',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=200, verbose_name=b'ascii name', db_index=True)),
                ('slug', models.CharField(max_length=200)),
                ('code', models.CharField(max_length=20)),
                ('location', django.contrib.gis.db.models.fields.PointField(srid=4326)),
                ('region_name', models.CharField(max_length=100, db_index=True)),
                ('subregion_name', models.CharField(max_length=100, db_index=True)),
                ('district_name', models.CharField(max_length=100, db_index=True)),
                ('alt_names', models.ManyToManyField(to='cities.AlternativeName')),
                ('country', models.ForeignKey(related_name='postal_codes', to='cities.Country')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Region',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=200, verbose_name=b'ascii name', db_index=True)),
                ('slug', models.CharField(max_length=200)),
                ('name_std', models.CharField(max_length=200, verbose_name=b'standard name', db_index=True)),
                ('code', models.CharField(max_length=200, db_index=True)),
                ('alt_names', models.ManyToManyField(to='cities.AlternativeName')),
                ('country', models.ForeignKey(to='cities.Country')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Subregion',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=200, verbose_name=b'ascii name', db_index=True)),
                ('slug', models.CharField(max_length=200)),
                ('name_std', models.CharField(max_length=200, verbose_name=b'standard name', db_index=True)),
                ('code', models.CharField(max_length=200, db_index=True)),
                ('alt_names', models.ManyToManyField(to='cities.AlternativeName')),
                ('region', models.ForeignKey(to='cities.Region')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.AddField(
            model_name='city',
            name='country',
            field=models.ForeignKey(to='cities.Country'),
        ),
        migrations.AddField(
            model_name='city',
            name='region',
            field=models.ForeignKey(blank=True, to='cities.Region', null=True),
        ),
        migrations.AddField(
            model_name='city',
            name='subregion',
            field=models.ForeignKey(blank=True, to='cities.Subregion', null=True),
        ),
    ]
Example #7
0
class Score(models.Model):
    """What the user scored for a given StudentItem at a given time.

    Note that while a Score *can* be tied to a Submission, it doesn't *have* to.
    Specifically, if we want to have scores for things that are not a part of
    the courseware (like "class participation"), there would be no corresponding
    Submission.
    """
    student_item = models.ForeignKey(StudentItem)
    submission = models.ForeignKey(Submission, null=True)
    points_earned = models.PositiveIntegerField(default=0)
    points_possible = models.PositiveIntegerField(default=0)
    created_at = models.DateTimeField(editable=False,
                                      default=now,
                                      db_index=True)

    # Flag to indicate that this score should reset the current "highest" score
    reset = models.BooleanField(default=False)

    class Meta:
        app_label = "submissions"

    @property
    def submission_uuid(self):
        """
        Retrieve the submission UUID associated with this score.
        If the score isn't associated with a submission (for example, if this is
        a "reset" score or a a non-courseware item like "class participation"),
        then this will return None.

        Returns:
            str or None

        """
        if self.submission is not None:
            return self.submission.uuid
        else:
            return None

    def to_float(self):
        """
        Calculate (points earned) / (points possible).
        If points possible is None (e.g. this is a "hidden" score)
        then return None.

        Returns:
            float or None

        """
        if self.points_possible == 0:
            return None
        return float(self.points_earned) / self.points_possible

    def __repr__(self):
        return repr(
            dict(
                student_item=self.student_item,
                submission=self.submission,
                created_at=self.created_at,
                points_earned=self.points_earned,
                points_possible=self.points_possible,
            ))

    def is_hidden(self):
        """
        By convention, a score of 0/0 is not displayed to users.
        Hidden scores are filtered by the submissions API.

        Returns:
            bool: Whether the score should be hidden.

        """
        return self.points_possible == 0

    @classmethod
    def create_reset_score(cls, student_item):
        """
        Create a "reset" score (a score with a null submission).

        Only scores created after the most recent "reset" score
        should be used to determine a student's effective score.

        Args:
            student_item (StudentItem): The student item model.

        Returns:
            Score: The newly created "reset" score.

        Raises:
            DatabaseError: An error occurred while creating the score

        """
        # By setting the "reset" flag, we ensure that the "highest"
        # score in the score summary will point to this score.
        # By setting points earned and points possible to 0,
        # we ensure that this score will be hidden from the user.
        return cls.objects.create(
            student_item=student_item,
            submission=None,
            points_earned=0,
            points_possible=0,
            reset=True,
        )

    def __unicode__(self):
        return u"{0.points_earned}/{0.points_possible}".format(self)
Example #8
0
class Migration(migrations.Migration):

    initial = True

    dependencies = []

    operations = [
        migrations.CreateModel(
            name='Author',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('full_name', models.TextField()),
                ('birth_year', models.SmallIntegerField()),
                ('country', models.CharField(max_length=2)),
            ],
        ),
        migrations.CreateModel(
            name='Friend',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('full_name', models.TextField()),
            ],
        ),
        migrations.CreateModel(
            name='Publisher',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('name', models.TextField()),
            ],
        ),
        migrations.CreateModel(
            name='Book',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('ISBN', models.CharField(max_length=13)),
                ('title', models.TextField()),
                ('description', models.TextField()),
                ('year_release', models.SmallIntegerField()),
                ('copy_count', models.SmallIntegerField(default=1)),
                ('price', models.DecimalField(decimal_places=2, max_digits=6)),
                ('borrowed_book_count', models.SmallIntegerField(default=0)),
                ('cover',
                 models.ImageField(blank=True,
                                   upload_to='covers',
                                   verbose_name='Обложка')),
                ('author',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='p_library.Author')),
                ('friend',
                 models.ManyToManyField(blank=True,
                                        related_name='friends',
                                        to='p_library.Friend')),
                ('publisher',
                 models.ForeignKey(blank=True,
                                   null=True,
                                   on_delete=django.db.models.deletion.CASCADE,
                                   related_name='books',
                                   to='p_library.Publisher')),
            ],
        ),
    ]
Example #9
0
class Migration(migrations.Migration):

    initial = True

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

    operations = [
        migrations.CreateModel(
            name='AboutUs',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(blank=True, max_length=255, null=True)),
                ('description', ckeditor.fields.RichTextField()),
            ],
            options={
                'verbose_name_plural': 'Haqqımızda',
            },
        ),
        migrations.CreateModel(
            name='Contact',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('address', models.CharField(blank=True, max_length=255, null=True)),
                ('office_hour', models.CharField(blank=True, max_length=255, null=True)),
                ('number', models.CharField(blank=True, max_length=255, null=True)),
                ('text', ckeditor.fields.RichTextField()),
            ],
            options={
                'verbose_name_plural': 'Əlaqə',
            },
        ),
        migrations.CreateModel(
            name='ContactUs',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=255)),
                ('email', models.EmailField(max_length=254)),
                ('subject', models.CharField(max_length=255)),
                ('desc', models.TextField()),
            ],
            options={
                'verbose_name_plural': 'Əlaqə Form',
            },
        ),
        migrations.CreateModel(
            name='Service',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=50)),
                ('description', models.CharField(max_length=100)),
                ('image', models.ImageField(blank=True, null=True, upload_to='services/')),
                ('fa_class', models.CharField(max_length=50)),
            ],
        ),
        migrations.CreateModel(
            name='Team',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(blank=True, max_length=255, null=True)),
                ('desc', ckeditor.fields.RichTextField()),
                ('status', models.CharField(blank=True, max_length=255, null=True)),
                ('email', models.EmailField(blank=True, max_length=254, null=True)),
                ('number', models.CharField(blank=True, max_length=255, null=True)),
                ('img', models.ImageField(upload_to='teams')),
                ('facebook', models.CharField(blank=True, max_length=255, null=True)),
                ('instagram', models.CharField(blank=True, max_length=255, null=True)),
                ('twitter', models.CharField(blank=True, max_length=255, null=True)),
            ],
            options={
                'verbose_name_plural': 'Komanda',
            },
        ),
        migrations.CreateModel(
            name='TextPages',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('team_member', models.CharField(blank=True, max_length=255, null=True)),
                ('team', models.CharField(blank=True, max_length=255, null=True)),
            ],
            options={
                'verbose_name_plural': 'Səhifə yazıları',
            },
        ),
        migrations.CreateModel(
            name='TeamServices',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('serv_name', models.CharField(blank=True, max_length=255, null=True)),
                ('service', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='kanatis_app.Team')),
            ],
            options={
                'verbose_name_plural': 'Komanda Servisləri',
            },
        ),
        migrations.CreateModel(
            name='SubService',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=30)),
                ('image', models.ImageField(upload_to='subservices/')),
                ('content', models.TextField()),
                ('fa_icon', models.CharField(max_length=50)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('service', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='kanatis_app.Service')),
            ],
        ),
        migrations.CreateModel(
            name='SertificateTeam',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('sertificate_name', models.CharField(blank=True, max_length=255, null=True)),
                ('sertificate', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='kanatis_app.Team')),
            ],
            options={
                'verbose_name_plural': 'Komanda Sertifikati',
            },
        ),
        migrations.CreateModel(
            name='Post',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=100)),
                ('content', models.TextField()),
                ('image', models.ImageField(upload_to='postimages/')),
                ('slug', models.SlugField(editable=False, null=True, unique=True)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
                ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='posts', to='kanatis_app.Service')),
            ],
            options={
                'ordering': ['-id'],
            },
        ),
        migrations.CreateModel(
            name='Carousel',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('content', models.CharField(max_length=100)),
                ('image', models.ImageField(upload_to='carousels/')),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('service', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='kanatis_app.Service')),
            ],
        ),
    ]
Example #10
0
class Migration(migrations.Migration):

    dependencies = [
        ('app', '0010_auto_20190110_2232'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='address',
            options={
                'verbose_name': 'адрес',
                'verbose_name_plural': 'адреса'
            },
        ),
        migrations.AlterModelOptions(
            name='customer',
            options={
                'verbose_name': 'клиент',
                'verbose_name_plural': 'клиенты'
            },
        ),
        migrations.AlterModelOptions(
            name='option',
            options={
                'verbose_name': 'опция',
                'verbose_name_plural': 'опции'
            },
        ),
        migrations.AlterModelOptions(
            name='order',
            options={
                'verbose_name': 'заказ',
                'verbose_name_plural': 'заказы'
            },
        ),
        migrations.AlterModelOptions(
            name='parameter',
            options={
                'verbose_name': 'параметр',
                'verbose_name_plural': 'параметры'
            },
        ),
        migrations.AlterModelOptions(
            name='phone',
            options={
                'verbose_name': 'телефон',
                'verbose_name_plural': 'телефоны'
            },
        ),
        migrations.AlterModelOptions(
            name='product',
            options={
                'verbose_name': 'товар',
                'verbose_name_plural': 'товары'
            },
        ),
        migrations.AlterModelOptions(
            name='producttype',
            options={
                'verbose_name': 'тип товаров',
                'verbose_name_plural': 'типы товаров'
            },
        ),
        migrations.AlterField(
            model_name='address',
            name='area',
            field=models.CharField(max_length=50, verbose_name='Область'),
        ),
        migrations.AlterField(
            model_name='address',
            name='building',
            field=models.CharField(default='',
                                   max_length=10,
                                   verbose_name='Корпус'),
        ),
        migrations.AlterField(
            model_name='address',
            name='city',
            field=models.CharField(max_length=50, verbose_name='Город'),
        ),
        migrations.AlterField(
            model_name='address',
            name='customer',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='app.Customer',
                verbose_name='Клиент'),
        ),
        migrations.AlterField(
            model_name='address',
            name='entrance',
            field=models.PositiveSmallIntegerField(verbose_name='Подъезд'),
        ),
        migrations.AlterField(
            model_name='address',
            name='flat',
            field=models.PositiveIntegerField(verbose_name='Квартира'),
        ),
        migrations.AlterField(
            model_name='address',
            name='floor',
            field=models.PositiveSmallIntegerField(verbose_name='Этаж'),
        ),
        migrations.AlterField(
            model_name='address',
            name='house',
            field=models.CharField(max_length=20, verbose_name='Дом'),
        ),
        migrations.AlterField(
            model_name='address',
            name='index',
            field=models.PositiveIntegerField(verbose_name='Индекс'),
        ),
        migrations.AlterField(
            model_name='address',
            name='street_name',
            field=models.CharField(max_length=50,
                                   verbose_name='Название улицы'),
        ),
        migrations.AlterField(
            model_name='address',
            name='street_type',
            field=models.CharField(choices=[('ул', 'улица'),
                                            ('пер', 'переулок'),
                                            ('пр', 'проезд'),
                                            ('бул', 'бульвар'),
                                            ('пл', 'площадь'), ('тр', 'тракт'),
                                            ('шс', 'шоссе')],
                                   default='ул',
                                   max_length=30,
                                   verbose_name='Тип улицы'),
        ),
        migrations.AlterField(
            model_name='option',
            name='name',
            field=models.CharField(max_length=100, verbose_name='Название'),
        ),
        migrations.AlterField(
            model_name='option',
            name='parameter',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='app.Parameter',
                verbose_name='Параметр'),
        ),
        migrations.AlterField(
            model_name='order',
            name='comment',
            field=models.TextField(default='', verbose_name='Комментарий'),
        ),
        migrations.AlterField(
            model_name='order',
            name='customer',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='app.Customer',
                verbose_name='Клиент'),
        ),
        migrations.AlterField(
            model_name='parameter',
            name='name',
            field=models.CharField(max_length=100, verbose_name='Название'),
        ),
        migrations.AlterField(
            model_name='phone',
            name='customer',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='app.Customer',
                verbose_name='Клиент'),
        ),
        migrations.AlterField(
            model_name='phone',
            name='number',
            field=models.CharField(max_length=30, verbose_name='Номер'),
        ),
        migrations.AlterField(
            model_name='product',
            name='comment',
            field=models.TextField(default='', verbose_name='Комментарий'),
        ),
        migrations.AlterField(
            model_name='product',
            name='name',
            field=models.CharField(max_length=200, verbose_name='Название'),
        ),
        migrations.AlterField(
            model_name='product',
            name='number',
            field=models.PositiveIntegerField(default=1,
                                              verbose_name='Количество'),
        ),
        migrations.AlterField(
            model_name='product',
            name='options',
            field=models.ManyToManyField(to='app.Option',
                                         verbose_name='Опции'),
        ),
        migrations.AlterField(
            model_name='product',
            name='order',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='app.Order',
                verbose_name='Заказ'),
        ),
        migrations.AlterField(
            model_name='product',
            name='price',
            field=models.FloatField(verbose_name='Цена продажи'),
        ),
        migrations.AlterField(
            model_name='product',
            name='purchase_price',
            field=models.FloatField(verbose_name='Закупочная цена'),
        ),
        migrations.AlterField(
            model_name='product',
            name='type',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='app.ProductType',
                verbose_name='Тип'),
        ),
        migrations.AlterField(
            model_name='producttype',
            name='name',
            field=models.CharField(max_length=50, verbose_name='Название'),
        ),
        migrations.AlterField(
            model_name='producttype',
            name='parameters',
            field=models.ManyToManyField(to='app.Parameter',
                                         verbose_name='Параметры'),
        ),
    ]
Example #11
0
class Migration(migrations.Migration):

    initial = True

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

    operations = [
        migrations.CreateModel(
            name='Event_Location',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('event_venue_name', models.CharField(max_length=200)),
                ('event_venue_addr', models.CharField(max_length=300)),
                ('event_latitude', models.CharField(max_length=100)),
                ('event_longitude', models.CharField(max_length=100)),
                ('event_name', models.CharField(max_length=200)),
            ],
        ),
        migrations.CreateModel(
            name='EventDetails',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('event', models.CharField(max_length=200)),
                ('expected_participant', models.IntegerField()),
                ('no_participant', models.IntegerField()),
                ('event_level', models.CharField(max_length=200)),
                ('eligibility', models.CharField(max_length=200)),
                ('prerequisite', models.TextField(max_length=1500)),
                ('facility', models.CharField(max_length=100)),
                ('event_detail_docs',
                 models.FileField(upload_to='images/event_details_docs/')),
            ],
        ),
        migrations.CreateModel(
            name='OrganiseEvent',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('event_title', models.CharField(max_length=200)),
                ('event_description', models.CharField(max_length=800)),
                ('event_category', models.CharField(max_length=200)),
                ('org_name', models.CharField(max_length=200)),
                ('org_email', models.EmailField(max_length=100)),
                ('org_mobile', models.BigIntegerField()),
                ('org_contact_person', models.CharField(max_length=100)),
                ('event_poster',
                 models.ImageField(default='images/noimage.png',
                                   upload_to='images/event_poster/')),
                ('event_startdate',
                 models.DateTimeField(default=django.utils.timezone.now)),
                ('event_enddate', models.DateTimeField()),
                ('us',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='ShareResource',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('event_title', models.CharField(max_length=100)),
                ('subject', models.CharField(max_length=100)),
                ('description', models.TextField(max_length=1500)),
                ('publishedDate',
                 models.DateTimeField(default=django.utils.timezone.now)),
                ('resourceLink', models.CharField(max_length=100)),
                ('documentFile',
                 models.FileField(upload_to='images/shared_resources_docs/')),
                ('publisedBy', models.CharField(max_length=100)),
                ('resourceImage',
                 models.ImageField(upload_to='images/shared_resources/')),
                ('org_id',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='Organizer.OrganiseEvent')),
                ('us',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='SponsorShip',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('event_title', models.CharField(default=True,
                                                 max_length=100)),
                ('platinum_sponsor', models.CharField(max_length=100)),
                ('f_platinum', models.TextField(max_length=1500)),
                ('ex_platinum', models.IntegerField()),
                ('gold_sponsor', models.CharField(max_length=100)),
                ('f_gold', models.TextField(max_length=1500)),
                ('ex_gold', models.IntegerField()),
                ('silver_sponsor', models.CharField(max_length=100)),
                ('f_silver', models.TextField(max_length=1500)),
                ('ex_silver', models.IntegerField()),
                ('org_id',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='Organizer.OrganiseEvent')),
                ('us',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.AddField(
            model_name='eventdetails',
            name='org_id',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='Organizer.OrganiseEvent'),
        ),
        migrations.AddField(
            model_name='eventdetails',
            name='us',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to=settings.AUTH_USER_MODEL),
        ),
        migrations.AddField(
            model_name='event_location',
            name='eventid',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to='Organizer.OrganiseEvent'),
        ),
    ]
Example #12
0
class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Command',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('command', models.CharField(max_length=200, verbose_name='命令')),
                ('result', models.CharField(max_length=2000, verbose_name='结果')),
                ('hosts_list', models.CharField(max_length=20000, verbose_name='执行机器')),
                ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
            ],
            options={
                'ordering': ['-create_time'],
            },
        ),
        migrations.CreateModel(
            name='Cron',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=64, unique=True, verbose_name='计划名称')),
                ('user', models.CharField(blank=True, default='root', max_length=256, null=True, verbose_name='执行用户')),
                ('job', models.CharField(max_length=1024, verbose_name='计划')),
                ('time', models.CharField(max_length=64, verbose_name='计划任务执行的时间')),
                ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
                ('note', models.CharField(blank=True, max_length=256, null=True, verbose_name='计划描述')),
            ],
            options={
                'ordering': ['-create_time'],
            },
        ),
        migrations.CreateModel(
            name='Host',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=200, unique=True, verbose_name='主机名')),
                ('hostip', models.GenericIPAddressField(verbose_name='主机ip地址')),
                ('env', models.CharField(choices=[('0', '开发'), ('1', '测试'), ('2', '预生产'), ('3', '生产')], default='3', max_length=20, verbose_name='环境')),
                ('version', models.CharField(blank=True, max_length=50, null=True, verbose_name='系统版本')),
                ('type', models.CharField(choices=[('0', 'nginx'), ('1', 'redis'), ('2', 'db'), ('3', 'server')], default='3', max_length=20, verbose_name='类型')),
                ('ssh_port', models.CharField(default=22, max_length=10, verbose_name='ssh端口')),
                ('status', models.CharField(choices=[('0', '在线'), ('1', '下线'), ('2', '维修')], default='0', max_length=2, verbose_name='状态')),
            ],
        ),
        migrations.CreateModel(
            name='Host_Issue',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('status', models.CharField(choices=[('0', '等待更新'), ('1', '更新中'), ('2', '等待测试'), ('3', '测试通过'), ('4', '更新完成'), ('5', '更新失败'), ('6', '回滚成功'), ('7', '回滚失败')], default='0', max_length=20, verbose_name='更新状态')),
                ('host', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.Host', verbose_name='发布机器')),
            ],
        ),
        migrations.CreateModel(
            name='Init',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=64, unique=True, verbose_name='名称')),
                ('function', models.CharField(max_length=64, unique=True, verbose_name='初始化功能')),
                ('play_book', models.CharField(max_length=100, verbose_name='playbook路径')),
                ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
            ],
            options={
                'ordering': ('-create_time',),
            },
        ),
        migrations.CreateModel(
            name='InitLog',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
                ('result', models.CharField(blank=True, max_length=1000, null=True, verbose_name='结果')),
                ('hosts_list', models.ManyToManyField(to='web.Host', verbose_name='执行机器')),
                ('init', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.Init', verbose_name='初始化功能')),
            ],
            options={
                'ordering': ('-create_time',),
            },
        ),
        migrations.CreateModel(
            name='Issue',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
                ('type', models.CharField(choices=[('0', '文件'), ('1', 'git')], default='0', max_length=20, verbose_name='更新类型')),
                ('status', models.CharField(choices=[('0', '等待更新'), ('1', '更新中'), ('2', '等待测试'), ('3', '测试通过'), ('4', '更新完成'), ('5', '更新失败'), ('6', '回滚成功'), ('7', '回滚失败')], default='0', max_length=20, verbose_name='更新状态')),
                ('version', models.CharField(blank=True, max_length=100, null=True, verbose_name='版本')),
                ('backup', models.CharField(choices=[('0', '是'), ('1', '否')], default='0', max_length=20, verbose_name='备份状态')),
                ('backup_path', models.CharField(blank=True, max_length=2048, null=True, verbose_name='备份文件路径')),
                ('upload_path', models.CharField(blank=True, max_length=2048, null=True, verbose_name='上传文件路径')),
            ],
            options={
                'ordering': ['-create_time'],
            },
        ),
        migrations.CreateModel(
            name='Team',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=200, unique=True, verbose_name='项目名')),
                ('path', models.CharField(max_length=200, verbose_name='项目目录')),
                ('git_path', models.CharField(max_length=200, verbose_name='git地址')),
                ('nginx_conf', models.CharField(blank=True, max_length=200, null=True, verbose_name='nginx配置文件')),
                ('language', models.CharField(choices=[('0', 'python'), ('1', 'java'), ('2', 'go'), ('3', 'php'), ('4', 'html')], default='0', max_length=20, verbose_name='语言')),
                ('domain', models.CharField(blank=True, max_length=100, null=True, verbose_name='域名')),
                ('note', models.CharField(blank=True, max_length=218, null=True, verbose_name='备注信息')),
                ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
                ('status', models.CharField(choices=[('0', '可用'), ('1', '下线')], default='0', max_length=2, verbose_name='状态')),
            ],
            options={
                'ordering': ('-create_time',),
            },
        ),
        migrations.CreateModel(
            name='UserProfile',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=200, verbose_name='用户名称')),
                ('email', models.CharField(max_length=200, verbose_name='邮箱地址')),
                ('password', models.CharField(max_length=200, verbose_name='密码')),
                ('role', models.CharField(choices=[('0', '开发'), ('1', '测试'), ('2', '运维')], default='0', max_length=10, verbose_name='角色')),
                ('is_admin', models.CharField(choices=[('0', 'Admin'), ('1', '普通')], default='1', max_length=10, verbose_name='管理员')),
                ('is_unable', models.CharField(choices=[('0', '可用'), ('1', '不可用')], default='0', max_length=10, verbose_name='是否可用')),
                ('department', models.CharField(blank=True, max_length=10, null=True, verbose_name='部门')),
                ('phone', models.CharField(blank=True, max_length=11, null=True, verbose_name='手机号')),
                ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
            ],
            options={
                'ordering': ['-create_time'],
            },
        ),
        migrations.AddField(
            model_name='team',
            name='boss',
            field=models.ManyToManyField(related_name='boss', to='web.UserProfile', verbose_name='责任人'),
        ),
        migrations.AddField(
            model_name='team',
            name='dev_user',
            field=models.ManyToManyField(related_name='dev_user', to='web.UserProfile', verbose_name='研发人员'),
        ),
        migrations.AddField(
            model_name='team',
            name='nginx_host',
            field=models.ManyToManyField(related_name='nginxhost', to='web.Host', verbose_name='nginx机器'),
        ),
        migrations.AddField(
            model_name='team',
            name='ops_user',
            field=models.ManyToManyField(related_name='ops_user', to='web.UserProfile', verbose_name='运维人员'),
        ),
        migrations.AddField(
            model_name='team',
            name='server_host',
            field=models.ManyToManyField(related_name='host', to='web.Host', verbose_name='后端主机'),
        ),
        migrations.AddField(
            model_name='team',
            name='test_user',
            field=models.ManyToManyField(related_name='test_user', to='web.UserProfile', verbose_name='测试人员'),
        ),
        migrations.AddField(
            model_name='issue',
            name='team',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.Team', verbose_name='发布项目'),
        ),
        migrations.AddField(
            model_name='issue',
            name='user',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.UserProfile', verbose_name='发布人'),
        ),
        migrations.AddField(
            model_name='initlog',
            name='user',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.UserProfile', verbose_name='创建者'),
        ),
        migrations.AddField(
            model_name='init',
            name='create_user',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.UserProfile', verbose_name='创建者'),
        ),
        migrations.AddField(
            model_name='host_issue',
            name='issue',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.Issue', verbose_name='更新'),
        ),
        migrations.AddField(
            model_name='host_issue',
            name='team',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.Team', verbose_name='发布项目'),
        ),
        migrations.AddField(
            model_name='cron',
            name='create_user',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.UserProfile', verbose_name='创建者'),
        ),
        migrations.AddField(
            model_name='cron',
            name='hosts_list',
            field=models.ManyToManyField(to='web.Host', verbose_name='执行机器'),
        ),
        migrations.AddField(
            model_name='command',
            name='user',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.UserProfile', verbose_name='用户'),
        ),
    ]
Example #13
0
class Tag(models.Model):
    name = models.CharField('Tag name',max_length=32,unique=True )
    creater = models.ForeignKey('UserProfile')
    create_date = models.DateField(auto_now_add=True)
    def __str__(self):
        return self.name
Example #14
0
class MediaFile(models.Model):
    filename = models.FileField()
    by = models.ForeignKey(Member)
    upload_date = models.DateField(auto_now_add=True)
Example #15
0
class Project(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    project_name = models.TextField(max_length=50, default="")
class ActivitySheetItem(models.Model):
    class Meta:
        app_label = 'tenant_foundation'
        db_table = 'workery_activity_sheet_items'
        verbose_name = _('Activity Sheet Item')
        verbose_name_plural = _('Activity Sheet Items')
        ordering = ['-created_at']
        default_permissions = ()
        permissions = (
            ("can_get_activity_sheet_items", "Can get activity sheets"),
            ("can_get_activity_sheet_item", "Can get activity sheet"),
            ("can_post_activity_sheet_item", "Can create activity sheet"),
            ("can_put_activity_sheet_item", "Can update activity sheet"),
            ("can_delete_activity_sheet_item", "Can delete activity sheet"),
        )

    objects = ActivitySheetItemManager()
    id = models.BigAutoField(
       primary_key=True,
       default=increment_activity_sheet_item_id_number,
       editable=False,
       db_index=True
    )

    #
    #  FIELDS
    #

    job = models.ForeignKey(
        "WorkOrder",
        help_text=_('The job associated with thie activity sheet item.'),
        related_name="activity_sheet_items",
        on_delete=models.CASCADE,
        blank=True,
        null=True,
    )
    ongoing_job = models.ForeignKey(
        "OngoingWorkOrder",
        help_text=_('The ongoing job associated with thie activity sheet item.'),
        related_name="activity_sheet_items",
        on_delete=models.CASCADE,
        blank=True,
        null=True
    )
    associate = models.ForeignKey(
        "Associate",
        help_text=_('The associate with this activity sheet item.'),
        related_name="activity_sheet_items",
        on_delete=models.CASCADE,
    )
    comment = models.TextField(
        _("Comment"),
        help_text=_('A comment associated with this activity sheet item.'),
        blank=True,
        null=True,
        default='',
    )
    state = FSMField(
        _('State'),
        help_text=_('The state of this activity sheet item for the job offer.'),
        default=ACTIVITY_SHEET_ITEM_STATE.PENDING,
        blank=True,
        db_index=True,
    )
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    created_by = models.ForeignKey(
        SharedUser,
        help_text=_('The user whom created this activity sheet item.'),
        related_name="created_activity_sheet_items",
        on_delete=models.SET_NULL,
        blank=True,
        null=True
    )
    created_from = models.GenericIPAddressField(
        _("Created from"),
        help_text=_('The IP address of the creator.'),
        blank=True,
        null=True
    )
    created_from_is_public = models.BooleanField(
        _("Is the IP "),
        help_text=_('Is creator a public IP and is routable.'),
        default=False,
        blank=True
    )

    #
    #  FUNCTIONS
    #

    def __str__(self):
        return str(self.job)+" "+str(self.associate)+" - "+str(self.id)
Example #17
0
class Migration(migrations.Migration):

    dependencies = [
        ('core', '0068_suite_version'),
    ]

    operations = [
        migrations.CreateModel(
            name='SuiteMetadata',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('suite', models.CharField(max_length=256)),
                ('kind',
                 models.CharField(choices=[('suite', 'Suite'),
                                           ('test', 'Test'),
                                           ('metric', 'Metric')],
                                  max_length=6)),
                ('name', models.CharField(max_length=256, null=True)),
                ('description', models.TextField(blank=True, null=True)),
                ('instructions_to_reproduce',
                 models.TextField(blank=True, null=True)),
            ],
            options={
                'verbose_name_plural': 'Suite metadata',
            },
        ),
        migrations.AlterUniqueTogether(
            name='suitemetadata',
            unique_together=set([('kind', 'suite', 'name')]),
        ),
        migrations.AddField(
            model_name='metric',
            name='metadata',
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name='+',
                to='core.SuiteMetadata'),
        ),
        migrations.AddField(
            model_name='suite',
            name='metadata',
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name='+',
                to='core.SuiteMetadata'),
        ),
        migrations.AddField(
            model_name='test',
            name='metadata',
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name='+',
                to='core.SuiteMetadata'),
        ),
    ]
Example #18
0
class Document(TimeStampedModel, InsertableModel, UpdateableModel):
    DocumentId = models.AutoField(primary_key=True, null=False)
    BasePartyId = models.ForeignKey(
        BaseParty,
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    # Temp field type / In the future will be foreign key
    CreditApplicationId = models.ForeignKey(
        CreditApplication,
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    DocumentType = models.ForeignKey(
        DocumentType,
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    DocumentStatus = models.ForeignKey(
        DocumentStatus,
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    Name1 = models.CharField(max_length=50, null=True, blank=True, default=None)
    Name2 = models.CharField(max_length=50, null=True, blank=True, default=None)
    Description1 = models.CharField(max_length=50, null=True, blank=True, default=None)
    Description2 = models.CharField(max_length=50, null=True, blank=True, default=None)
    DocumentIdType = models.ForeignKey(
        DocumentIdType,
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    CharDocumentId = models.CharField(max_length=50, null=True, blank=True, default=None)
    # FileType = models.ForeignKey(
    #     FileType,
    #     on_delete=models.CASCADE,
    #     default=None, null=True, blank=True
    # )
    FileType = models.CharField(max_length=100, null=True, blank=True)
    FileName = models.CharField(max_length=200, null=True, blank=True, default=None)
    FileURL = models.CharField(max_length=200, null=True, blank=True, default=None)
    # FileSize = models.FloatField(null=True, blank=True, default=None)
    FileSize = models.CharField(max_length=100, null=True, blank=True)
    DocumentStoreType = models.ForeignKey(
        DocumentStoreType,
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    DocumentStore = models.ForeignKey(
        DocumentStore,
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    Frequency = models.ForeignKey(
        Frequency,
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    DocumentDateFirst = models.DateTimeField(null=True, blank=True, default=None)
    DocumentDateNext = models.DateTimeField(null=True, blank=True, default=None)
    DocumentDateLast = models.DateTimeField(null=True, blank=True, default=None)
    ExpectedDocuments = models.IntegerField(null=True, blank=True, default=None)
    SkipEvery = models.IntegerField(null=True, blank=True, default=None)
    StartSkip = models.IntegerField(null=True, blank=True, default=None)
    # Temp field type / In the future will be foreign key
    AlertEnabledFlag = models.IntegerField(null=True, blank=True, default=None)
    AlertDays = models.IntegerField(null=True, blank=True, default=None)
    AlertDocumentStatus = models.ForeignKey(
        AlertDocumentStatus,
        related_name='AlertDocumentStatus',
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    AlertSource = models.ForeignKey(
        AlertSource,
        related_name='AlertSource',
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    AlertType = models.ForeignKey(
        AlertType,
        related_name='AsdAlertType',
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    AlertSubType = models.ForeignKey(
        AlertSubType,
        related_name='AlertSubType',
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    AlertSeverity = models.ForeignKey(
        AlertSeverity,
        related_name='AlertSeverity',
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    AlertStatus = models.ForeignKey(
        AlertStatus,
        related_name='AlertStatus',
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    # Temp field type / In the future will be foreign key
    AlertTemplateId = models.IntegerField(null=True, blank=True, default=None)
    # Temp field type / In the future will be foreign key
    AlertEmailFlag = models.IntegerField(null=True, blank=True, default=None)
    AlertEmailOption = models.ForeignKey(
        AlertEmailOption,
        related_name='AlertEmailOption',
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    # Temp field type / In the future will be foreign key
    AlertSenderId = models.IntegerField(null=True, blank=True, default=None)
    AlertRecipientId = models.TextField(null=True, blank=True, default=None)
    AlertBasePartyEmailId = models.TextField(null=True, blank=True, default=None)
    AlertConvertOption = models.ForeignKey(
        AlertConvertOption,
        related_name='AlertConvertOption',
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    # Temp field type / In the future will be foreign key
    WarningEnabledFlag = models.IntegerField(null=True, blank=True, default=None)
    WarningDays = models.IntegerField(null=True, blank=True, default=None)
    WarningDocumentStatus = models.ForeignKey(
        'common.AlertDocumentStatus',
        related_name='WarningDocumentStatus',
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    WarningSource = models.ForeignKey(
        'common.AlertSource',
        related_name='WarningSource',
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    WarningType = models.ForeignKey(
        'common.AlertType',
        related_name='WarningType',
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    WarningSubType = models.ForeignKey(
        'common.AlertSubType',
        related_name='WarningSubType',
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    WarningSeverity = models.ForeignKey(
        'common.AlertSeverity',
        related_name='WarningSeverity',
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    WarningStatus = models.ForeignKey(
        'common.AlertStatus',
        related_name='WarningStatus',
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    # Temp field type / In the future will be foreign key
    WarningTemplateId = models.IntegerField(null=True, blank=True, default=None)
    # Temp field type / In the future will be foreign key
    WarningEmailFlag = models.IntegerField(null=True, blank=True, default=None)
    WarningEmailOption = models.ForeignKey(
        'common.AlertEmailOption',
        related_name='WarningEmailOption',
        on_delete=models.CASCADE,
        default=None, null=True, blank=True
    )
    # Temp field type / In the future will be foreign key
    WarningSenderId = models.IntegerField(null=True, blank=True, default=None)
    WarningRecipientId = models.TextField(null=True, blank=True, default=None)
    WarningBasePartyEmailId = models.TextField(null=True, blank=True, default=None)

    StorageLocation = models.IntegerField(null=True, blank=True)
    FirstUploadDate = models.DateTimeField(null=True, blank=True, default=None)
    LastVerifyDate = models.DateTimeField(null=True, blank=True, default=None)
    LastClearDate = models.DateTimeField(null=True, blank=True, default=None)
    FirstUploadBy = models.ForeignKey(
        get_user_model(),
        related_name='FirstUploadBy',
        on_delete=models.CASCADE,
        default=None, null=True, blank=True,
    )
    LastVerifyBy = models.ForeignKey(
        get_user_model(),
        related_name='LastVerifyBy',
        on_delete=models.CASCADE,
        default=None, null=True, blank=True,
    )
    LastClearanceBy = models.ForeignKey(
        get_user_model(),
        related_name='LastClearanceBy',
        on_delete=models.CASCADE,
        default=None, null=True, blank=True,
    )

    objects = models.Manager()

    def __str__(self):
        return '{}'.format(self.DocumentId)

    class Meta:
        verbose_name = 'Document'
        verbose_name_plural = 'Document'
        db_table = 'Document'
Example #19
0
class Choice(models.Model):
        question = models.ForeignKey(Question,
                    on_delete=models.CASCADE)
        choice_text = models.CharField(max_length=200)
        votes = models.IntegerField(default=0)
Example #20
0
class ReportersCounter(models.Model):

    COUNTS_SQUASH_LOCK = 'org-reporters-counts-squash-lock'
    LAST_SQUASHED_ID_KEY = 'org-reporters-last-squashed-id'

    org = models.ForeignKey(Org, related_name='reporters_counters')

    type = models.CharField(max_length=255)

    count = models.IntegerField(default=0, help_text=_("Number of items with this counter"))

    @classmethod
    def squash_counts(cls):
        # get the id of the last count we squashed
        r = get_redis_connection()
        key = ReportersCounter.COUNTS_SQUASH_LOCK
        if r.get(key):
            print "Squash reporters counts already running."
        else:
            with r.lock(key):

                last_squash = r.get(ReportersCounter.LAST_SQUASHED_ID_KEY)
                if not last_squash:
                    last_squash = 0

                start = time.time()
                squash_count = 0

                if last_squash < 1:
                    counters = ReportersCounter.objects.values('org_id', 'type').annotate(Count('id')).filter(id__count__gt=1).order_by('org_id', 'type')

                else:
                    counters = ReportersCounter.objects.filter(id__gt=last_squash).values('org_id', 'type').order_by('org_id', 'type').distinct('org_id', 'type')

                total_counters = len(counters)

                # get all the new added counters
                for counter in counters:

                    # perform our atomic squash in SQL by calling our squash method
                    with connection.cursor() as c:
                        c.execute("SELECT ureport_squash_reporterscounters(%s, %s);", (counter['org_id'], counter['type']))

                    squash_count += 1

                    if squash_count % 100 == 0:
                        print "Squashing progress ... %0.2f/100 in in %0.3fs" % (squash_count * 100 / total_counters, time.time() - start)

                # insert our new top squashed id
                max_id = ReportersCounter.objects.all().order_by('-id').first()
                if max_id:
                    r.set(ReportersCounter.LAST_SQUASHED_ID_KEY, max_id.id)

                print "Squashed poll results counts for %d types in %0.3fs" % (squash_count, time.time() - start)

    @classmethod
    def get_counts(cls, org, types=None):
        """
        Gets all reporters counts by counter type for the given org
        """
        counters = cls.objects.filter(org=org)
        if types:
            counters = counters.filter(type__in=types)
        counter_counts = counters.values('type').order_by('type').annotate(count_sum=Sum('count'))

        return {c['type']: c['count_sum'] for c in counter_counts}

    class Meta:
        index_together = ('org', 'type')
Example #21
0
class Migration(migrations.Migration):

    initial = True

    dependencies = []

    operations = [
        migrations.CreateModel(
            name='Cart',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('total_products', models.PositiveIntegerField(default=0)),
                ('final_price',
                 models.DecimalField(decimal_places=2,
                                     default=0,
                                     max_digits=9,
                                     verbose_name='Общая цена')),
                ('in_order', models.BooleanField(default=False)),
                ('for_anonymous_user', models.BooleanField(default=False)),
            ],
        ),
        migrations.CreateModel(
            name='CartProduct',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('qty', models.PositiveIntegerField(default=1)),
                ('final_price',
                 models.DecimalField(decimal_places=2,
                                     max_digits=9,
                                     verbose_name='Общая цена')),
            ],
        ),
        migrations.CreateModel(
            name='Category',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('name',
                 models.CharField(max_length=255,
                                  verbose_name='Имя категории')),
                ('slug', models.SlugField(unique=True)),
            ],
        ),
        migrations.CreateModel(
            name='Customer',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('phone',
                 models.CharField(blank=True,
                                  max_length=20,
                                  null=True,
                                  verbose_name='Номер телефона')),
                ('address',
                 models.CharField(blank=True,
                                  max_length=255,
                                  null=True,
                                  verbose_name='Адрес')),
            ],
        ),
        migrations.CreateModel(
            name='Order',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('first_name',
                 models.CharField(max_length=255, verbose_name='Имя')),
                ('last_name',
                 models.CharField(max_length=255, verbose_name='Фамилия')),
                ('phone',
                 models.CharField(max_length=20, verbose_name='Телефон')),
                ('address',
                 models.CharField(blank=True,
                                  max_length=1024,
                                  null=True,
                                  verbose_name='Адрес')),
                ('status',
                 models.CharField(choices=[('new', 'Новый заказ'),
                                           ('in_progress',
                                            'Заказ в обработке'),
                                           ('is_ready', 'Заказ готов'),
                                           ('completed', 'Заказ выполнен')],
                                  default='new',
                                  max_length=100,
                                  verbose_name='Статус заказ')),
                ('buying_type',
                 models.CharField(choices=[('self', 'Самовывоз'),
                                           ('delivery', 'Доставка')],
                                  default='self',
                                  max_length=100,
                                  verbose_name='Тип заказа')),
                ('comment',
                 models.TextField(blank=True,
                                  null=True,
                                  verbose_name='Комментарий к заказу')),
                ('created_at',
                 models.DateTimeField(auto_now=True,
                                      verbose_name='Дата создания заказа')),
                ('order_date',
                 models.DateField(default=django.utils.timezone.now,
                                  verbose_name='Дата получения заказа')),
            ],
        ),
        migrations.CreateModel(
            name='Product',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('title',
                 models.CharField(max_length=255,
                                  verbose_name='Наименование')),
                ('slug', models.SlugField(unique=True)),
                ('image',
                 models.ImageField(upload_to='', verbose_name='Изображение')),
                ('description',
                 models.TextField(null=True, verbose_name='Описание')),
                ('price',
                 models.DecimalField(decimal_places=2,
                                     max_digits=9,
                                     verbose_name='Цена')),
                ('category',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='mainapp.category',
                                   verbose_name='Категория')),
            ],
        ),
    ]
Example #22
0
class Ticket(models.Model):
    """
    To allow a ticket to be entered as quickly as possible, only the
    bare minimum fields are required. These basically allow us to
    sort and manage the ticket. The user can always go back and
    enter more information later.

    A good example of this is when a customer is on the phone, and
    you want to give them a ticket ID as quickly as possible. You can
    enter some basic info, save the ticket, give the customer the ID
    and get off the phone, then add in further detail at a later time
    (once the customer is not on the line).

    Note that assigned_to is optional - unassigned tickets are displayed on
    the dashboard to prompt users to take ownership of them.
    """

    OPEN_STATUS = 1
    REOPENED_STATUS = 2
    RESOLVED_STATUS = 3
    CLOSED_STATUS = 4
    DUPLICATE_STATUS = 5

    STATUS_CHOICES = (
        (OPEN_STATUS, _('Open')),
        (REOPENED_STATUS, _('Reopened')),
        (RESOLVED_STATUS, _('Resolved')),
        (CLOSED_STATUS, _('Closed')),
        (DUPLICATE_STATUS, _('Duplicate')),
    )

    PRIORITY_CHOICES = (
        (1, _('1. Critical')),
        (2, _('2. High')),
        (3, _('3. Normal')),
        (4, _('4. Low')),
        (5, _('5. Very Low')),
    )

    title = models.CharField(
        _('Title'),
        max_length=200,
        )

    queue = models.ForeignKey(
        Queue,
        verbose_name=_('Queue'),
        )

    created = models.DateTimeField(
        _('Created'),
        blank=True,
        help_text=_('Date this ticket was first created'),
        )

    modified = models.DateTimeField(
        _('Modified'),
        blank=True,
        help_text=_('Date this ticket was most recently changed.'),
        )

    submitter_email = models.EmailField(
        _('Submitter E-Mail'),
        blank=True,
        null=True,
        help_text=_('The submitter will receive an email for all public '
            'follow-ups left for this task.'),
        )

    assigned_to = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        related_name='assigned_to',
        blank=True,
        null=True,
        verbose_name=_('Assigned to'),
        )

    status = models.IntegerField(
        _('Status'),
        choices=STATUS_CHOICES,
        default=OPEN_STATUS,
        )

    on_hold = models.BooleanField(
        _('On Hold'),
        blank=True,
        default=False,
        help_text=_('If a ticket is on hold, it will not automatically be '
            'escalated.'),
        )

    description = models.TextField(
        _('Description'),
        blank=True,
        null=True,
        help_text=_('The content of the customers query.'),
        )

    resolution = models.TextField(
        _('Resolution'),
        blank=True,
        null=True,
        help_text=_('The resolution provided to the customer by our staff.'),
        )

    priority = models.IntegerField(
        _('Priority'),
        choices=PRIORITY_CHOICES,
        default=3,
        blank=3,
        help_text=_('1 = Highest Priority, 5 = Low Priority'),
        )

    due_date = models.DateTimeField(
        _('Due on'),
        blank=True,
        null=True,
        )

    last_escalation = models.DateTimeField(
        blank=True,
        null=True,
        editable=False,
        help_text=_('The date this ticket was last escalated - updated '
            'automatically by management/commands/escalate_tickets.py.'),
        )

    def _get_assigned_to(self):
        """ Custom property to allow us to easily print 'Unassigned' if a
        ticket has no owner, or the users name if it's assigned. If the user
        has a full name configured, we use that, otherwise their username. """
        if not self.assigned_to:
            return _('Unassigned')
        else:
            if self.assigned_to.get_full_name():
                return self.assigned_to.get_full_name()
            else:
                return self.assigned_to.get_username()
    get_assigned_to = property(_get_assigned_to)

    def _get_ticket(self):
        """ A user-friendly ticket ID, which is a combination of ticket ID
        and queue slug. This is generally used in e-mail subjects. """

        return u"[%s]" % (self.ticket_for_url)
    ticket = property(_get_ticket)

    def _get_ticket_for_url(self):
        """ A URL-friendly ticket ID, used in links. """
        return u"%s-%s" % (self.queue.slug, self.id)
    ticket_for_url = property(_get_ticket_for_url)

    def _get_priority_img(self):
        """ Image-based representation of the priority """
        from django.conf import settings
        return u"%shelpdesk/priorities/priority%s.png" % (settings.MEDIA_URL, self.priority)
    get_priority_img = property(_get_priority_img)

    def _get_priority_css_class(self):
        """
        Return the boostrap class corresponding to the priority.
        """
        if self.priority == 2:
            return "warning"
        elif self.priority == 1:
            return "danger"
        else:
            return ""
    get_priority_css_class = property(_get_priority_css_class)

    def _get_status(self):
        """
        Displays the ticket status, with an "On Hold" message if needed.
        """
        held_msg = ''
        if self.on_hold: held_msg = _(' - On Hold')
        dep_msg = ''
        if self.can_be_resolved == False: dep_msg = _(' - Open dependencies')
        return u'%s%s%s' % (self.get_status_display(), held_msg, dep_msg)
    get_status = property(_get_status)

    def _get_ticket_url(self):
        """
        Returns a publicly-viewable URL for this ticket, used when giving
        a URL to the submitter of a ticket.
        """
        from django.contrib.sites.models import Site
        from django.core.urlresolvers import reverse
        try:
            site = Site.objects.get_current()
        except:
            site = Site(domain='configure-django-sites.com')
        return u"http://%s%s?ticket=%s&email=%s" % (
            site.domain,
            reverse('helpdesk_public_view'),
            self.ticket_for_url,
            self.submitter_email
            )
    ticket_url = property(_get_ticket_url)

    def _get_staff_url(self):
        """
        Returns a staff-only URL for this ticket, used when giving a URL to
        a staff member (in emails etc)
        """
        from django.contrib.sites.models import Site
        from django.core.urlresolvers import reverse
        try:
            site = Site.objects.get_current()
        except:
            site = Site(domain='configure-django-sites.com')
        return u"http://%s%s" % (
            site.domain,
            reverse('helpdesk_view',
            args=[self.id])
            )
    staff_url = property(_get_staff_url)

    def _can_be_resolved(self):
        """
        Returns a boolean.
        True = any dependencies are resolved
        False = There are non-resolved dependencies
        """
        OPEN_STATUSES = (Ticket.OPEN_STATUS, Ticket.REOPENED_STATUS)
        return TicketDependency.objects.filter(ticket=self).filter(depends_on__status__in=OPEN_STATUSES).count() == 0
    can_be_resolved = property(_can_be_resolved)

    class Meta:
        get_latest_by = "created"
        ordering = ('id',)
        verbose_name = _('Ticket')
        verbose_name_plural = _('Tickets')

    def __unicode__(self):
        return u'%s %s' % (self.id, self.title)

    def get_absolute_url(self):
        return ('helpdesk_view', (self.id,))
    get_absolute_url = models.permalink(get_absolute_url)

    def save(self, *args, **kwargs):
        if not self.id:
            # This is a new ticket as no ID yet exists.
            self.created = timezone.now()

        if not self.priority:
            self.priority = 3

        self.modified = timezone.now()

        super(Ticket, self).save(*args, **kwargs)
Example #23
0
class Solution(models.Model):

    class Meta:
        verbose_name = "решение задачи"
        verbose_name_plural = "решения задач"

    MS__NOT_CHECKED = '0'
    MS__READY_TO_CHECK = '1'
    MS__CHECK_IN_PROGRESS = '2'
    MS__CHECKED = '3'
    MS__AWAITING_CHECK = (MS__READY_TO_CHECK, MS__CHECK_IN_PROGRESS)
    MS__CHOICES = (
        (MS__NOT_CHECKED, 'нет'),
        (MS__READY_TO_CHECK, 'ожидает проверки'),
        (MS__CHECK_IN_PROGRESS, 'в процессе проверки'),
        (MS__CHECKED, 'проверено'),
    )

    S__NONE = '0'
    S__UNLUCK = '1'
    S__IN_PROGRESS = '2'
    S__SUCCESS = '3'
    S__CHOICES = (
        (S__NONE, 'нет попыток'),
        (S__UNLUCK, 'нет решения'),
        (S__IN_PROGRESS, 'частично решено'),
        (S__SUCCESS, 'решено'),
    )

    taskitem = models.ForeignKey(TaskItem, verbose_name='задача', related_name='solutions')
    user = models.ForeignKey(UserModel, verbose_name="пользователь")
    datetime = models.DateTimeField(verbose_name='дата создания', auto_now_add=True)
    last_modified = models.DateTimeField(verbose_name="дата последней отправки", auto_now_add=True)
    is_count = models.BooleanField(verbose_name="баллы идут в зачет", default=True)
    is_locked = models.BooleanField(verbose_name="запрещено изменять", default=False)
    manual_status = models.CharField(
        verbose_name='статус проверки преподавателем', max_length=255,
        choices=MS__CHOICES, default=MS__NOT_CHECKED
    )
    manual_score = models.FloatField(verbose_name='оценка преподавателя', blank=True, null=True)
    tests_score = models.FloatField(verbose_name='оценка по автотестам', blank=True, null=True)

    last_changes = models.TextField(verbose_name="последние изменения", blank=True, default='')
    content = models.TextField(verbose_name="листинг решения", blank=True, default='')
    version_list = JSONField(verbose_name="список сохраненных решений", default=list, blank=True, null=True)
    comment = HTMLField(verbose_name="комментарий к решению", blank=True, null=True)
    teacher = models.ForeignKey(
        UserModel, verbose_name='преподаватель', blank=True, null=True, related_name='controlled_solutions',
        help_text='заполняется автоматически, когда преподаватель выставляет оценку'
    )

    @property
    def score(self):

        """ Оценка преподавателя имеет больший приоритет чем оценка по автотестам """

        if self.taskitem.manual_check:
            if self.manual_status == self.MS__CHECKED:
                return self.manual_score
            else:
                return None
        else:
            return self.tests_score

    @property
    def status(self) -> str:

        """ Статус вычисляется на основе оценки """

        if self.score is None:
            return self.S__NONE
        elif self.score <= 0:
            return self.S__UNLUCK
        elif self.score >= self.taskitem.max_score:
            return self.S__SUCCESS
        else:
            return self.S__IN_PROGRESS

    @property
    def status_name(self) -> str:

        """ Возващает текст статуса """

        status = self.status
        for choice in self.S__CHOICES:
            if choice[0] == status:
                return choice[1]

    @property
    def manual_status_name(self):
        for choice in self.MS__CHOICES:
            if choice[0] == self.manual_status:
                return choice[1]

    def create_version(self, content):

        """ Создать верисю решения задачи """

        if len(self.version_list) == 10:
            self.version_list.pop(0)
        self.version_list.append({
            "datetime": str(timezone.now().strftime(format='%Y-%m-%d %H:%M:%S.%f')),
            "content": content,
        })

    def set_is_count(self):

        """ Если время на решение задачи истеко то решение вне зачета """

        if self.taskitem.topic.end_time is not None:
            self.is_count = timezone.now() <= self.taskitem.topic.end_time

    def get_breadcrumbs(self):
        return [
            {'title': 'Курсы', 'url': reverse('training:courses')},
            {'title': self.taskitem.topic.course.title,   'url': self.taskitem.topic.course.get_absolute_url()},
            {'title': self.taskitem.topic.numbered_title, 'url': self.taskitem.topic.get_absolute_url()},
            {'title': self.taskitem.numbered_title,       'url': self.taskitem.get_absolute_url()},
        ]

    def get_absolute_url(self):
        return reverse(
            'training:solution',
            kwargs={
                'course': self.taskitem.topic.course.slug,
                'topic': self.taskitem.topic.slug,
                'taskitem': self.taskitem.slug
            }
        )

    def __str__(self):
        return '%s: %s' % (self.user.get_full_name(), self.taskitem.title)

    def __repr__(self):
        return f"Solution: {self.__str__()}"
Example #24
0
class FollowUp(models.Model):
    """
    A FollowUp is a comment and/or change to a ticket. We keep a simple
    title, the comment entered by the user, and the new status of a ticket
    to enable easy flagging of details on the view-ticket page.

    The title is automatically generated at save-time, based on what action
    the user took.

    Tickets that aren't public are never shown to or e-mailed to the submitter,
    although all staff can see them.
    """

    ticket = models.ForeignKey(
        Ticket,
        verbose_name=_('Ticket'),
        )

    date = models.DateTimeField(
        _('Date'),
        default = timezone.now
        )

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

    comment = models.TextField(
        _('Comment'),
        blank=True,
        null=True,
        )

    public = models.BooleanField(
        _('Public'),
        blank=True,
        default=False,
        help_text=_('Public tickets are viewable by the submitter and all '
            'staff, but non-public tickets can only be seen by staff.'),
        )

    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        blank=True,
        null=True,
        verbose_name=_('User'),
        )

    new_status = models.IntegerField(
        _('New Status'),
        choices=Ticket.STATUS_CHOICES,
        blank=True,
        null=True,
        help_text=_('If the status was changed, what was it changed to?'),
        )

    objects = FollowUpManager()

    class Meta:
        ordering = ['date']
        verbose_name = _('Follow-up')
        verbose_name_plural = _('Follow-ups')

    def __unicode__(self):
        return u'%s' % self.title

    def get_absolute_url(self):
        return u"%s#followup%s" % (self.ticket.get_absolute_url(), self.id)

    def save(self, *args, **kwargs):
        t = self.ticket
        t.modified = timezone.now()
        t.save()
        super(FollowUp, self).save(*args, **kwargs)
Example #25
0
class Cable(PrimaryModel, StatusModel):
    """
    A physical connection between two endpoints.
    """

    termination_a_type = models.ForeignKey(
        to=ContentType,
        limit_choices_to=CABLE_TERMINATION_MODELS,
        on_delete=models.PROTECT,
        related_name="+",
    )
    termination_a_id = models.UUIDField()
    termination_a = GenericForeignKey(ct_field="termination_a_type",
                                      fk_field="termination_a_id")
    termination_b_type = models.ForeignKey(
        to=ContentType,
        limit_choices_to=CABLE_TERMINATION_MODELS,
        on_delete=models.PROTECT,
        related_name="+",
    )
    termination_b_id = models.UUIDField()
    termination_b = GenericForeignKey(ct_field="termination_b_type",
                                      fk_field="termination_b_id")
    type = models.CharField(max_length=50,
                            choices=CableTypeChoices,
                            blank=True)
    label = models.CharField(max_length=100, blank=True)
    color = ColorField(blank=True)
    length = models.PositiveSmallIntegerField(blank=True, null=True)
    length_unit = models.CharField(
        max_length=50,
        choices=CableLengthUnitChoices,
        blank=True,
    )
    # Stores the normalized length (in meters) for database ordering
    _abs_length = models.DecimalField(max_digits=10,
                                      decimal_places=4,
                                      blank=True,
                                      null=True)
    # Cache the associated device (where applicable) for the A and B terminations. This enables filtering of Cables by
    # their associated Devices.
    _termination_a_device = models.ForeignKey(to=Device,
                                              on_delete=models.CASCADE,
                                              related_name="+",
                                              blank=True,
                                              null=True)
    _termination_b_device = models.ForeignKey(to=Device,
                                              on_delete=models.CASCADE,
                                              related_name="+",
                                              blank=True,
                                              null=True)

    csv_headers = [
        "termination_a_type",
        "termination_a_id",
        "termination_b_type",
        "termination_b_id",
        "type",
        "status",
        "label",
        "color",
        "length",
        "length_unit",
    ]

    class Meta:
        ordering = [
            "termination_a_type",
            "termination_a_id",
            "termination_b_type",
            "termination_b_id",
        ]
        unique_together = (
            ("termination_a_type", "termination_a_id"),
            ("termination_b_type", "termination_b_id"),
        )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # A copy of the PK to be used by __str__ in case the object is deleted
        self._pk = self.pk

        if self.present_in_database:
            # Cache the original status so we can check later if it's been changed
            self._orig_status = self.status
        else:
            self._orig_status = None

    def __str__(self):
        pk = self.pk or self._pk
        return self.label or f"#{pk}"

    def get_absolute_url(self):
        return reverse("dcim:cable", args=[self.pk])

    @classproperty
    def STATUS_CONNECTED(cls):
        """Return a cached "connected" `Status` object for later reference."""
        if getattr(cls, "__status_connected", None) is None:
            cls.__status_connected = Status.objects.get_for_model(Cable).get(
                slug="connected")
        return cls.__status_connected

    def clean(self):
        super().clean()

        # We import this in this method due to circular importing issues.
        from nautobot.circuits.models import CircuitTermination

        # Validate that termination A exists
        if not hasattr(self, "termination_a_type"):
            raise ValidationError("Termination A type has not been specified")
        try:
            self.termination_a_type.model_class().objects.get(
                pk=self.termination_a_id)
        except ObjectDoesNotExist:
            raise ValidationError({
                "termination_a":
                "Invalid ID for type {}".format(self.termination_a_type)
            })

        # Validate that termination B exists
        if not hasattr(self, "termination_b_type"):
            raise ValidationError("Termination B type has not been specified")
        try:
            self.termination_b_type.model_class().objects.get(
                pk=self.termination_b_id)
        except ObjectDoesNotExist:
            raise ValidationError({
                "termination_b":
                "Invalid ID for type {}".format(self.termination_b_type)
            })

        # If editing an existing Cable instance, check that neither termination has been modified.
        if self.present_in_database:
            err_msg = "Cable termination points may not be modified. Delete and recreate the cable instead."

            existing_obj = Cable.objects.get(pk=self.pk)

            if (self.termination_a_type_id !=
                    existing_obj.termination_a_type_id
                    or self.termination_a_id != existing_obj.termination_a_id):
                raise ValidationError({"termination_a": err_msg})
            if (self.termination_b_type_id !=
                    existing_obj.termination_b_type_id
                    or self.termination_b_id != existing_obj.termination_b_id):
                raise ValidationError({"termination_b": err_msg})

        type_a = self.termination_a_type.model
        type_b = self.termination_b_type.model

        # Validate interface types
        if type_a == "interface" and self.termination_a.type in NONCONNECTABLE_IFACE_TYPES:
            raise ValidationError({
                "termination_a_id":
                "Cables cannot be terminated to {} interfaces".format(
                    self.termination_a.get_type_display())
            })
        if type_b == "interface" and self.termination_b.type in NONCONNECTABLE_IFACE_TYPES:
            raise ValidationError({
                "termination_b_id":
                "Cables cannot be terminated to {} interfaces".format(
                    self.termination_b.get_type_display())
            })

        # Check that termination types are compatible
        if type_b not in COMPATIBLE_TERMINATION_TYPES.get(type_a):
            raise ValidationError(
                f"Incompatible termination types: {self.termination_a_type} and {self.termination_b_type}"
            )

        # Check that two connected RearPorts have the same number of positions (if both are >1)
        if isinstance(self.termination_a, RearPort) and isinstance(
                self.termination_b, RearPort):
            if self.termination_a.positions > 1 and self.termination_b.positions > 1:
                if self.termination_a.positions != self.termination_b.positions:
                    raise ValidationError(
                        f"{self.termination_a} has {self.termination_a.positions} position(s) but "
                        f"{self.termination_b} has {self.termination_b.positions}. "
                        f"Both terminations must have the same number of positions (if greater than one)."
                    )

        # A termination point cannot be connected to itself
        if self.termination_a == self.termination_b:
            raise ValidationError(
                f"Cannot connect {self.termination_a_type} to itself")

        # A front port cannot be connected to its corresponding rear port
        if (type_a in ["frontport", "rearport"]
                and type_b in ["frontport", "rearport"] and
            (getattr(self.termination_a, "rear_port", None)
             == self.termination_b or getattr(self.termination_b, "rear_port",
                                              None) == self.termination_a)):
            raise ValidationError(
                "A front port cannot be connected to it corresponding rear port"
            )

        # A CircuitTermination attached to a Provider Network cannot have a Cable
        if isinstance(self.termination_a, CircuitTermination
                      ) and self.termination_a.provider_network is not None:
            raise ValidationError({
                "termination_a_id":
                "Circuit terminations attached to a provider network may not be cabled."
            })
        if isinstance(self.termination_b, CircuitTermination
                      ) and self.termination_b.provider_network is not None:
            raise ValidationError({
                "termination_b_id":
                "Circuit terminations attached to a provider network may not be cabled."
            })

        # Check for an existing Cable connected to either termination object
        if self.termination_a.cable not in (None, self):
            raise ValidationError(
                "{} already has a cable attached (#{})".format(
                    self.termination_a, self.termination_a.cable_id))
        if self.termination_b.cable not in (None, self):
            raise ValidationError(
                "{} already has a cable attached (#{})".format(
                    self.termination_b, self.termination_b.cable_id))

        # Validate length and length_unit
        if self.length is not None and not self.length_unit:
            raise ValidationError(
                "Must specify a unit when setting a cable length")
        elif self.length is None:
            self.length_unit = ""

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

        # Store the given length (if any) in meters for use in database ordering
        if self.length and self.length_unit:
            self._abs_length = to_meters(self.length, self.length_unit)
        else:
            self._abs_length = None

        # Store the parent Device for the A and B terminations (if applicable) to enable filtering
        if hasattr(self.termination_a, "device"):
            self._termination_a_device = self.termination_a.device
        if hasattr(self.termination_b, "device"):
            self._termination_b_device = self.termination_b.device

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

        # Update the private pk used in __str__ in case this is a new object (i.e. just got its pk)
        self._pk = self.pk

    def to_csv(self):
        return (
            "{}.{}".format(self.termination_a_type.app_label,
                           self.termination_a_type.model),
            self.termination_a_id,
            "{}.{}".format(self.termination_b_type.app_label,
                           self.termination_b_type.model),
            self.termination_b_id,
            self.get_type_display(),
            self.get_status_display(),
            self.label,
            self.color,
            self.length,
            self.length_unit,
        )

    def get_compatible_types(self):
        """
        Return all termination types compatible with termination A.
        """
        if self.termination_a is None:
            return
        return COMPATIBLE_TERMINATION_TYPES[
            self.termination_a._meta.model_name]
Example #26
0
class KBItem(models.Model):
    """
    An item within the knowledgebase. Very straightforward question/answer
    style system.
    """
    category = models.ForeignKey(
        KBCategory,
        verbose_name=_('Category'),
        )

    title = models.CharField(
        _('Title'),
        max_length=100,
        )

    question = models.TextField(
        _('Question'),
        )

    answer = models.TextField(
        _('Answer'),
        )

    votes = models.IntegerField(
        _('Votes'),
        help_text=_('Total number of votes cast for this item'),
        default=0,
        )

    recommendations = models.IntegerField(
        _('Positive Votes'),
        help_text=_('Number of votes for this item which were POSITIVE.'),
        default=0,
        )

    last_updated = models.DateTimeField(
        _('Last Updated'),
        help_text=_('The date on which this question was most recently '
            'changed.'),
        blank=True,
        )

    def save(self, *args, **kwargs):
        if not self.last_updated:
            self.last_updated = timezone.now()
        return super(KBItem, self).save(*args, **kwargs)

    def _score(self):
        if self.votes > 0:
            return int(self.recommendations / self.votes)
        else:
            return _('Unrated')
    score = property(_score)

    def __unicode__(self):
        return u'%s' % self.title

    class Meta:
        ordering = ['title',]
        verbose_name = _('Knowledge base item')
        verbose_name_plural = _('Knowledge base items')

    def get_absolute_url(self):
        return ('helpdesk_kb_item', (self.id,))
    get_absolute_url = models.permalink(get_absolute_url)
Example #27
0
class Teacher(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)    

    def __str__(self):
        return self.user.username
class Migration(migrations.Migration):

    dependencies = [
        ('transcription', '0003_auto_20170329_1410'),
    ]

    operations = [
        migrations.CreateModel(
            name='Annotation',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('type', models.CharField(default='0', help_text='Sorry, no help available for annotation.type', max_length=5, verbose_name='Kind of annotation')),
                ('mode', models.CharField(blank=True, help_text='Sorry, no help available for annotation.mode', max_length=5, verbose_name='Annotation mode')),
                ('format', models.CharField(blank=True, help_text='Sorry, no help available for annotation.format', max_length=5, verbose_name='Annotation format')),
            ],
        ),
        migrations.CreateModel(
            name='Anonymisation',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(default='0', help_text='Sorry, no help available for anonymisation', max_length=5, verbose_name='Anonymisation level of the transcription')),
            ],
            options={
                'verbose_name_plural': 'Anonymisation levels',
            },
        ),
        migrations.CreateModel(
            name='Availability',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(default='0', help_text='Sorry, no help available for interview.availability', max_length=5, verbose_name='Availability')),
            ],
            options={
                'verbose_name_plural': 'Availability descriptions',
            },
        ),
        migrations.CreateModel(
            name='FileFormat',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(default='0', help_text='Sorry, no help available for interview.format', max_length=5, verbose_name='Format of audio/video file')),
            ],
        ),
        migrations.CreateModel(
            name='Genre',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(default='0', help_text='Sorry, no help available for interview.genre', max_length=5, verbose_name='Genre of this transcription')),
            ],
        ),
        migrations.CreateModel(
            name='Language',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(default='0', help_text='Sorry, no help available for interview.language', max_length=5, verbose_name='Language in collection')),
            ],
        ),
        migrations.CreateModel(
            name='Participant',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('code', models.CharField(help_text='Sorry, no help available for participant.code', max_length=255, verbose_name='Code for this person')),
                ('name', models.CharField(help_text='Sorry, no help available for participant.name', max_length=255, verbose_name='Name of the person')),
                ('gender', models.CharField(default='0', help_text='Sorry, no help available for participant.gender', max_length=5, verbose_name='Gender of the person')),
                ('age', models.CharField(help_text='Sorry, no help available for participant.age', max_length=255, verbose_name='Age of the person')),
            ],
        ),
        migrations.CreateModel(
            name='SpatialCoverage',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('country', models.CharField(default='0', help_text='Sorry, no help available for coverage.spatial.country', max_length=5, verbose_name='Country included in this spatial coverage')),
                ('place', models.CharField(blank=True, help_text='Sorry, no help available for coverage.spatial.city', max_length=80, verbose_name='Place (city) for this spatial coverage')),
            ],
            options={
                'verbose_name_plural': 'Spatial coverages',
            },
        ),
        migrations.CreateModel(
            name='TemporalCoverage',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('startYear', models.CharField(default='2017', max_length=20, verbose_name='First year covered by the transcription')),
                ('endYear', models.CharField(default='2017', max_length=20, verbose_name='Last year covered by the transcription')),
            ],
            options={
                'verbose_name_plural': 'Spatial coverages',
            },
        ),
        migrations.AddField(
            model_name='descriptor',
            name='copyright',
            field=models.TextField(blank=True, help_text='Sorry, no help available for interview.copyright', verbose_name='Copyright for this transcription'),
        ),
        migrations.AddField(
            model_name='descriptor',
            name='interviewDate',
            field=models.DateField(blank=True, default=datetime.datetime.today, help_text='Sorry, no help available for interview.date', verbose_name='Date of the interview'),
        ),
        migrations.AddField(
            model_name='descriptor',
            name='interviewId',
            field=models.CharField(default='-', help_text='Sorry, no help available for interview.id', max_length=255, verbose_name='Interview ID'),
        ),
        migrations.AddField(
            model_name='descriptor',
            name='interviewLength',
            field=models.TimeField(blank=True, default='00:00:00', help_text='Sorry, no help available for interview.length', verbose_name='Length in time of the interview'),
        ),
        migrations.AddField(
            model_name='descriptor',
            name='modality',
            field=models.CharField(default='0', help_text='Sorry, no help available for interview.modality', max_length=5, verbose_name='Transcription modality'),
        ),
        migrations.AddField(
            model_name='descriptor',
            name='owner',
            field=models.CharField(default='-', max_length=255, verbose_name='Unique short descriptor identifier (10 characters max)'),
        ),
        migrations.AddField(
            model_name='descriptor',
            name='projectTitle',
            field=models.CharField(default='-', help_text='Sorry, no help available for project.title', max_length=255, verbose_name='Project title'),
        ),
        migrations.AddField(
            model_name='descriptor',
            name='topicList',
            field=models.TextField(blank=True, help_text='Sorry, no help available for interview.topiclist', verbose_name='List of topics for this transcription'),
        ),
        migrations.AlterField(
            model_name='descriptor',
            name='identifier',
            field=models.CharField(default='-', max_length=10, verbose_name='Unique short descriptor identifier (10 characters max)'),
        ),
        migrations.CreateModel(
            name='Interviewee',
            fields=[
                ('participant_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='transcription.Participant')),
                ('descriptor', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='interviewees', to='transcription.Descriptor')),
            ],
            options={
                'verbose_name_plural': 'Persons that were interviewed',
            },
            bases=('transcription.participant',),
        ),
        migrations.CreateModel(
            name='Interviewer',
            fields=[
                ('participant_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='transcription.Participant')),
                ('descriptor', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='interviewers', to='transcription.Descriptor')),
            ],
            options={
                'verbose_name_plural': 'Interviewers',
            },
            bases=('transcription.participant',),
        ),
        migrations.AddField(
            model_name='temporalcoverage',
            name='descriptor',
            field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='temporalcoverages', to='transcription.Descriptor'),
        ),
        migrations.AddField(
            model_name='spatialcoverage',
            name='descriptor',
            field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='spatialcoverages', to='transcription.Descriptor'),
        ),
        migrations.AddField(
            model_name='language',
            name='descriptor',
            field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='languages', to='transcription.Descriptor'),
        ),
        migrations.AddField(
            model_name='genre',
            name='descriptor',
            field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='genres', to='transcription.Descriptor'),
        ),
        migrations.AddField(
            model_name='fileformat',
            name='descriptor',
            field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='fileformats', to='transcription.Descriptor'),
        ),
        migrations.AddField(
            model_name='availability',
            name='descriptor',
            field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='availabilities', to='transcription.Descriptor'),
        ),
        migrations.AddField(
            model_name='anonymisation',
            name='descriptor',
            field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='anonymisations', to='transcription.Descriptor'),
        ),
        migrations.AddField(
            model_name='annotation',
            name='descriptor',
            field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='annotations', to='transcription.Descriptor'),
        ),
    ]
Example #29
0
class Order(models.Model):
    # user = models.ForeignKey(User)
    date = models.DateTimeField(auto_now_add=True)
    content = models.TextField(max_length=160)
    owner = models.ForeignKey(User, related_name="order_owner")
Example #30
0
class Blog(models.Model):
    author = models.ForeignKey('Author', on_delete=models.CASCADE)
    title = models.CharField(max_length=255)