Ejemplo n.º 1
0
 def test_unique_together(self):
     """
     Tests removing and adding unique_together constraints on a model.
     """
     # Create the table
     with connection.schema_editor() as editor:
         editor.create_model(UniqueTest)
     # Ensure the fields are unique to begin with
     UniqueTest.objects.create(year=2012, slug="foo")
     UniqueTest.objects.create(year=2011, slug="foo")
     UniqueTest.objects.create(year=2011, slug="bar")
     self.assertRaises(IntegrityError, UniqueTest.objects.create, year=2012, slug="foo")
     UniqueTest.objects.all().delete()
     # Alter the model to it's non-unique-together companion
     with connection.schema_editor() as editor:
         editor.alter_unique_together(UniqueTest, UniqueTest._meta.unique_together, [])
     # Ensure the fields are no longer unique
     UniqueTest.objects.create(year=2012, slug="foo")
     UniqueTest.objects.create(year=2012, slug="foo")
     UniqueTest.objects.all().delete()
     # Alter it back
     new_new_field = SlugField(unique=True)
     new_new_field.set_attributes_from_name("slug")
     with connection.schema_editor() as editor:
         editor.alter_unique_together(UniqueTest, [], UniqueTest._meta.unique_together)
     # Ensure the fields are unique again
     UniqueTest.objects.create(year=2012, slug="foo")
     self.assertRaises(IntegrityError, UniqueTest.objects.create, year=2012, slug="foo")
     UniqueTest.objects.all().delete()
Ejemplo n.º 2
0
 def test_index_together(self):
     """
     Tests removing and adding index_together constraints on a model.
     """
     # Create the table
     with connection.schema_editor() as editor:
         editor.create_model(Tag)
     # Ensure there's no index on the year/slug columns first
     self.assertEqual(
         False,
         any(c["index"] for c in self.get_constraints("schema_tag").values() if c["columns"] == ["slug", "title"]),
     )
     # Alter the model to add an index
     with connection.schema_editor() as editor:
         editor.alter_index_together(Tag, [], [("slug", "title")])
     # Ensure there is now an index
     self.assertEqual(
         True,
         any(c["index"] for c in self.get_constraints("schema_tag").values() if c["columns"] == ["slug", "title"]),
     )
     # Alter it back
     new_new_field = SlugField(unique=True)
     new_new_field.set_attributes_from_name("slug")
     with connection.schema_editor() as editor:
         editor.alter_index_together(Tag, [("slug", "title")], [])
     # Ensure there's no index
     self.assertEqual(
         False,
         any(c["index"] for c in self.get_constraints("schema_tag").values() if c["columns"] == ["slug", "title"]),
     )
Ejemplo n.º 3
0
 def test_primary_key(self):
     """
     Tests altering of the primary key
     """
     # Create the table
     with connection.schema_editor() as editor:
         editor.create_model(Tag)
     # Ensure the table is there and has the right PK
     self.assertTrue(
         self.get_indexes(Tag._meta.db_table)['id']['primary_key'],
     )
     # Alter to change the PK
     new_field = SlugField(primary_key=True)
     new_field.set_attributes_from_name("slug")
     new_field.model = Tag
     with connection.schema_editor() as editor:
         editor.remove_field(Tag, Tag._meta.get_field_by_name("id")[0])
         editor.alter_field(
             Tag,
             Tag._meta.get_field_by_name("slug")[0],
             new_field,
         )
     # Ensure the PK changed
     self.assertNotIn(
         'id',
         self.get_indexes(Tag._meta.db_table),
     )
     self.assertTrue(
         self.get_indexes(Tag._meta.db_table)['slug']['primary_key'],
     )
Ejemplo n.º 4
0
 def test_SlugField(self):
     lazy_func = lazy(lambda: 'slug', six.text_type)
     self.assertIsInstance(SlugField().get_prep_value(lazy_func()),
                           six.text_type)
     lazy_func = lazy(lambda: 0, int)
     self.assertIsInstance(SlugField().get_prep_value(lazy_func()),
                           six.text_type)
Ejemplo n.º 5
0
class Repository(models.Model):
    owner = CharField(max_length=100)
    name = CharField(max_length=100)
    slug = SlugField(max_length=201)
    host_slug = SlugField(max_length=302, unique=True)
    language = CharField(max_length=100, null=True)
    html_url = URLField(null=True, max_length=400)
    homepage = URLField(null=True, max_length=400)
    watchers = PositiveIntegerField(null=True)
    created_at = DateTimeField(null=True)
    pushed_at = DateTimeField(null=True)
    description = TextField(null=True)
    extra_data = JSONField(null=True)
    last_modified = DateTimeField(auto_now=True)
    scm = CharField(max_length=100, choices=SCM_CHOICES, null=True)
    host = CharField(max_length=100, choices=HOST_CHOICES)
    private = BooleanField(default=False)

    class Meta:
        unique_together = ("owner", "name", "host")
        ordering = ['-watchers']

    def save(self, *args, **kwargs):
        self.slug = self.owner.lower() + '/' + self.name.lower()
        self.host_slug = self.host + '/' + self.slug
        if self.html_url == None or self.html_url == '':
            if self.host == 'bitbucket':
                self.html_url = 'https://bitbucket.org/%s/%s' % (self.owner,
                                                                 self.name)
            if self.host == 'github':
                self.html_url = 'https://github.com/%s/%s' % (self.owner,
                                                              self.name)

        super(Repository, self).save(*args, **kwargs)
Ejemplo n.º 6
0
 def test_primary_key(self):
     """
     Tests altering of the primary key
     """
     # Create the table
     with connection.schema_editor() as editor:
         editor.create_model(Tag)
     # Ensure the table is there and has the right PK
     self.assertTrue(
         connection.introspection.get_indexes(
             connection.cursor(),
             Tag._meta.db_table)['id']['primary_key'], )
     # Alter to change the PK
     new_field = SlugField(primary_key=True)
     new_field.set_attributes_from_name("slug")
     new_field.model = Tag
     with connection.schema_editor() as editor:
         editor.remove_field(Tag, Tag._meta.get_field_by_name("id")[0])
         editor.alter_field(
             Tag,
             Tag._meta.get_field_by_name("slug")[0],
             new_field,
         )
     # Ensure the PK changed
     self.assertNotIn(
         'id',
         connection.introspection.get_indexes(connection.cursor(),
                                              Tag._meta.db_table),
     )
     self.assertTrue(
         connection.introspection.get_indexes(
             connection.cursor(),
             Tag._meta.db_table)['slug']['primary_key'], )
Ejemplo n.º 7
0
 def test_index_together(self):
     """
     Tests removing and adding index_together constraints on a model.
     """
     # Create the table
     with connection.schema_editor() as editor:
         editor.create_model(Tag)
     # Ensure there's no index on the year/slug columns first
     self.assertEqual(
         False,
         any(
             c["index"]
             for c in self.get_constraints("schema_tag").values()
             if c['columns'] == ["slug", "title"]
         ),
     )
     # Alter the model to add an index
     with connection.schema_editor() as editor:
         editor.alter_index_together(
             Tag,
             [],
             [("slug", "title")],
         )
     # Ensure there is now an index
     self.assertEqual(
         True,
         any(
             c["index"]
             for c in self.get_constraints("schema_tag").values()
             if c['columns'] == ["slug", "title"]
         ),
     )
     # Alter it back
     new_new_field = SlugField(unique=True)
     new_new_field.set_attributes_from_name("slug")
     with connection.schema_editor() as editor:
         editor.alter_index_together(
             Tag,
             [("slug", "title")],
             [],
         )
     # Ensure there's no index
     self.assertEqual(
         False,
         any(
             c["index"]
             for c in self.get_constraints("schema_tag").values()
             if c['columns'] == ["slug", "title"]
         ),
     )
Ejemplo n.º 8
0
 def test_unique(self):
     """
     Tests removing and adding unique constraints to a single column.
     """
     # Create the table
     with connection.schema_editor() as editor:
         editor.create_model(Tag)
     # Ensure the field is unique to begin with
     Tag.objects.create(title="foo", slug="foo")
     self.assertRaises(IntegrityError, Tag.objects.create, title="bar", slug="foo")
     Tag.objects.all().delete()
     # Alter the slug field to be non-unique
     new_field = SlugField(unique=False)
     new_field.set_attributes_from_name("slug")
     with connection.schema_editor() as editor:
         editor.alter_field(
             Tag,
             Tag._meta.get_field_by_name("slug")[0],
             new_field,
             strict=True,
         )
     # Ensure the field is no longer unique
     Tag.objects.create(title="foo", slug="foo")
     Tag.objects.create(title="bar", slug="foo")
     Tag.objects.all().delete()
     # Alter the slug field to be unique
     new_new_field = SlugField(unique=True)
     new_new_field.set_attributes_from_name("slug")
     with connection.schema_editor() as editor:
         editor.alter_field(
             Tag,
             new_field,
             new_new_field,
             strict=True,
         )
     # Ensure the field is unique again
     Tag.objects.create(title="foo", slug="foo")
     self.assertRaises(IntegrityError, Tag.objects.create, title="bar", slug="foo")
     Tag.objects.all().delete()
     # Rename the field
     new_field = SlugField(unique=False)
     new_field.set_attributes_from_name("slug2")
     with connection.schema_editor() as editor:
         editor.alter_field(
             Tag,
             Tag._meta.get_field_by_name("slug")[0],
             TagUniqueRename._meta.get_field_by_name("slug2")[0],
             strict=True,
         )
     # Ensure the field is still unique
     TagUniqueRename.objects.create(title="foo", slug2="foo")
     self.assertRaises(IntegrityError, TagUniqueRename.objects.create, title="bar", slug2="foo")
     Tag.objects.all().delete()
Ejemplo n.º 9
0
class EventoBase(Model, CT):
    categoria = ForeignKey(CategoriaEvento)
    title = CharField('titulo', max_length=250)
    description = TextField('descripción', blank=True, null=True)
    slug = SlugField(db_index=True)
    rating = GenericRelation(Rating)
    start = DateTimeField('comienzo')
    end = DateTimeField('fin')
    precio = CharField('precio', max_length=250)
    poster = ImageField(upload_to='cartelera/posters', blank=True, null=True)
    type = CharField(max_length=250)

    def __unicode__(self):
        return self.title

    def render(self):
        return render_to_string(
            [
                'cartelera/%s_lead.html' % self.categoria.slug,
                'cartelera/evento_lead.html'
            ],
            {'%s' % self.categoria.slug: self},
        )

    def get_absolute_url(self):
        return reverse('evento', kwargs={'slug': self.slug})
Ejemplo n.º 10
0
class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('flow', '0001_squashed_0030_change_slug_field'),
    ]

    operations = [
        migrations.CreateModel(
            name='Sample',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('slug', SlugField(editable=True, max_length=100)),
                ('version', versionfield.VersionField(default=0)),
                ('name', models.CharField(max_length=100)),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('modified', models.DateTimeField(auto_now=True)),
                ('description', models.TextField(blank=True)),
                ('settings',
                 django.contrib.postgres.fields.jsonb.JSONField(default={})),
                ('descriptor',
                 django.contrib.postgres.fields.jsonb.JSONField(default={})),
                ('collections', models.ManyToManyField(to='flow.Collection')),
                ('contributor',
                 models.ForeignKey(on_delete=django.db.models.deletion.PROTECT,
                                   to=settings.AUTH_USER_MODEL)),
                ('data', models.ManyToManyField(to='flow.Data')),
                ('descriptor_schema',
                 models.ForeignKey(blank=True,
                                   null=True,
                                   on_delete=django.db.models.deletion.PROTECT,
                                   to='flow.DescriptorSchema')),
                ('public_processes',
                 models.ManyToManyField(to='flow.Process')),
            ],
            options={
                'default_permissions': (),
                'abstract':
                False,
                'permissions':
                (('view_sample', 'Can view sample'),
                 ('edit_sample', 'Can edit sample'), ('share_sample',
                                                      'Can share sample'),
                 ('download_sample', 'Can download files from sample'),
                 ('add_sample', 'Can add data objects to sample')),
            },
        ),
        migrations.AlterUniqueTogether(
            name='sample',
            unique_together=set([('slug', 'version')]),
        ),
    ]
Ejemplo n.º 11
0
 def test_unique_together(self):
     """
     Tests removing and adding unique_together constraints on a model.
     """
     # Create the table
     with connection.schema_editor() as editor:
         editor.create_model(UniqueTest)
     # Ensure the fields are unique to begin with
     UniqueTest.objects.create(year=2012, slug="foo")
     UniqueTest.objects.create(year=2011, slug="foo")
     UniqueTest.objects.create(year=2011, slug="bar")
     self.assertRaises(IntegrityError,
                       UniqueTest.objects.create,
                       year=2012,
                       slug="foo")
     UniqueTest.objects.all().delete()
     # Alter the model to it's non-unique-together companion
     with connection.schema_editor() as editor:
         editor.alter_unique_together(
             UniqueTest,
             UniqueTest._meta.unique_together,
             [],
         )
     # Ensure the fields are no longer unique
     UniqueTest.objects.create(year=2012, slug="foo")
     UniqueTest.objects.create(year=2012, slug="foo")
     UniqueTest.objects.all().delete()
     # Alter it back
     new_new_field = SlugField(unique=True)
     new_new_field.set_attributes_from_name("slug")
     with connection.schema_editor() as editor:
         editor.alter_unique_together(
             UniqueTest,
             [],
             UniqueTest._meta.unique_together,
         )
     # Ensure the fields are unique again
     UniqueTest.objects.create(year=2012, slug="foo")
     self.assertRaises(IntegrityError,
                       UniqueTest.objects.create,
                       year=2012,
                       slug="foo")
     UniqueTest.objects.all().delete()
Ejemplo n.º 12
0
class Lugar(Model):
    nombre = CharField('nombre', max_length=100, blank=True, null=True)
    slug = SlugField(db_index=True)
    prepopulated_fields = {"slug": ("nombre", )}
    address = TextField('dirección', blank=True, null=True)
    phones = CharField('telefonos', max_length=250)

    class Meta:
        abstract = True

    def __unicode__(self):
        return self.nombre
Ejemplo n.º 13
0
class CategoriaEvento(Model):
    nombre = CharField('nombre', max_length=100, blank=True, null=True)
    order = PositiveSmallIntegerField(u'orden en cartelera', default=0)
    slug = SlugField(db_index=True)

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

    def __unicode__(self):
        return self.nombre

    def get_absolute_url(self):
        return reverse('categoria_evento', kwargs={'slug': self.slug})
Ejemplo n.º 14
0
class EventTaxonomyBase(models.Model):
    title = models.CharField(max_length=100)
    slug = SlugField()

    class Meta:
        abstract = True
        ordering = ["title"]

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super().save(*args, **kwargs)

    panels = [FieldPanel("title")]
Ejemplo n.º 15
0
class BaseGraphTemplate(GenericBaseModel):
    """
    GraphTemplateCategory class - inherits from GenericBaseModel
    """
    name = CharField(max_length=255, verbose_name=_('Name'))
    slug = SlugField(max_length=255, unique=True, verbose_name=_('Slug'))

    class Meta:
        #app_label   = 'graphs'
        verbose_name = _('Base Graph Template')
        verbose_name_plural = _('Base Graph Templates')

    def __unicode__(self):
        """
        Unicode function
        """
        return u'%s' % _(self.name)
Ejemplo n.º 16
0
class PlacesAndItems(models.Model):
    name = models.CharField(max_length=255)
    type = models.IntegerField(default=0)
    content = HTMLField()
    seo_desc = models.CharField(max_length=155, default='', blank=True)
    slug = SlugField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = MiscManager()

    story = models.ManyToManyField(MoonTrekStories,
                                   related_name='places',
                                   blank=True)

    def __str__(self):
        return f'Place/Item: { self.name }'

    def get_absolute_url(self):
        return reverse('LCARS:miscView', kwargs={'slug': self.slug})
Ejemplo n.º 17
0
class RepositoryUser(models.Model):
    login = CharField(max_length=100, db_index=True)
    name = CharField(max_length=100, null=True)
    slug = SlugField(max_length=201, unique=True)
    email = EmailField(max_length=254, null=True)
    blog = URLField(null=True)
    followers = PositiveIntegerField(null=True)
    following = PositiveIntegerField(null=True)
    public_repos = PositiveIntegerField(null=True)
    created_at = DateTimeField(null=True)
    extra_data = JSONField(null=True)
    last_modified = DateTimeField(auto_now=True)
    repositories = models.ManyToManyField(
        Repository, through='RepositoryUserRepositoryLink')
    starred = PositiveIntegerField(null=True)
    watched = PositiveIntegerField(null=True)
    host = CharField(max_length=100, choices=HOST_CHOICES, db_index=True)

    class Meta:
        unique_together = ("login", "host")

    def save(self, *args, **kwargs):
        self.slug = self.host + '/' + self.login.lower()
        super(RepositoryUser, self).save(*args, **kwargs)
Ejemplo n.º 18
0
 def test_SlugField(self):
     self.assertIsInstance(SlugField().get_prep_value('slug'), str)
     self.assertIsInstance(SlugField().get_prep_value(0), unicode)
Ejemplo n.º 19
0
    def test_unique(self):
        """
        Tests removing and adding unique constraints to a single column.
        """
        print('\n')
        # Create the table
        print('1. Create the table')
        with connection.schema_editor() as editor:
            editor.create_model(Tag)

        # Ensure the field is unique to begin with
        print('2. Ensure the field is unique to begin with')
        Tag.objects.create(title="foo", slug="foo")
        self.assertRaises(IntegrityError, Tag.objects.create, title="bar", slug="foo")
        Tag.objects.all().delete()

        # Alter the slug field to be non-unique
        print('3. Alter the slug field to be non-unique')
        new_field = SlugField(unique=False)
        new_field.set_attributes_from_name("slug")
        with connection.schema_editor() as editor:
            editor.alter_field(
                Tag,
                Tag._meta.get_field_by_name("slug")[0],
                new_field,
                strict=True,
            )

        # Ensure the field is no longer unique
        print('4. Ensure the field is no longer unique')
        Tag.objects.create(title="foo", slug="foo")
        Tag.objects.create(title="bar", slug="foo")
        Tag.objects.all().delete()

        # Alter the slug field to be unique
        print('5. Alter the slug field to be unique')
        new_new_field = SlugField(unique=True)
        new_new_field.set_attributes_from_name("slug")
        with connection.schema_editor() as editor:
            editor.alter_field(
                Tag,
                new_field,
                new_new_field,
                strict=True,
            )

        # Ensure the field is unique again
        print('6. Ensure the field is unique again')
        Tag.objects.create(title="foo", slug="foo")
        self.assertRaises(IntegrityError, Tag.objects.create, title="bar", slug="foo")
        Tag.objects.all().delete()

        # The code below fail...
        # Firebid 2.5.x does not allow rename a field with a unique constraint defined on it.
        # Thas is to preserve data integrity.
        # Cannot update index segment used by an Integrity Constraint', -607, 335544351
        return

        # Rename the field
        print('7. Rename the field')
        new_field = SlugField(unique=False)
        new_field.set_attributes_from_name("slug2")
        with connection.schema_editor() as editor:
            editor.alter_field(
                Tag,
                Tag._meta.get_field_by_name("slug")[0],
                TagUniqueRename._meta.get_field_by_name("slug2")[0],
                strict=True,
            )

        # Ensure the field is still unique
        print('8. Ensure the field is still unique')
        TagUniqueRename.objects.create(title="foo", slug2="foo")
        self.assertRaises(IntegrityError, TagUniqueRename.objects.create, title="bar", slug2="foo")
        Tag.objects.all().delete()
Ejemplo n.º 20
0
 def test_unique(self):
     """
     Tests removing and adding unique constraints to a single column.
     """
     # Create the table
     with connection.schema_editor() as editor:
         editor.create_model(Tag)
     # Ensure the field is unique to begin with
     Tag.objects.create(title="foo", slug="foo")
     self.assertRaises(IntegrityError,
                       Tag.objects.create,
                       title="bar",
                       slug="foo")
     Tag.objects.all().delete()
     # Alter the slug field to be non-unique
     new_field = SlugField(unique=False)
     new_field.set_attributes_from_name("slug")
     with connection.schema_editor() as editor:
         editor.alter_field(
             Tag,
             Tag._meta.get_field_by_name("slug")[0],
             new_field,
             strict=True,
         )
     # Ensure the field is no longer unique
     Tag.objects.create(title="foo", slug="foo")
     Tag.objects.create(title="bar", slug="foo")
     Tag.objects.all().delete()
     # Alter the slug field to be unique
     new_new_field = SlugField(unique=True)
     new_new_field.set_attributes_from_name("slug")
     with connection.schema_editor() as editor:
         editor.alter_field(
             Tag,
             new_field,
             new_new_field,
             strict=True,
         )
     # Ensure the field is unique again
     Tag.objects.create(title="foo", slug="foo")
     self.assertRaises(IntegrityError,
                       Tag.objects.create,
                       title="bar",
                       slug="foo")
     Tag.objects.all().delete()
     # Rename the field
     new_field = SlugField(unique=False)
     new_field.set_attributes_from_name("slug2")
     with connection.schema_editor() as editor:
         editor.alter_field(
             Tag,
             Tag._meta.get_field_by_name("slug")[0],
             TagUniqueRename._meta.get_field_by_name("slug2")[0],
             strict=True,
         )
     # Ensure the field is still unique
     TagUniqueRename.objects.create(title="foo", slug2="foo")
     self.assertRaises(IntegrityError,
                       TagUniqueRename.objects.create,
                       title="bar",
                       slug2="foo")
     Tag.objects.all().delete()
Ejemplo n.º 21
0
 def test_SlugField(self):
     self.assertIsInstance(SlugField().get_prep_value('slug'),
                           six.text_type)
     self.assertIsInstance(SlugField().get_prep_value(0), six.text_type)
Ejemplo n.º 22
0
class Room(Model):
    name = CharField(max_length=100)
    label = SlugField(unique=True)

    def __str__(self):
        return '<Room - %s>' % self.label
Ejemplo n.º 23
0
class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ("flow", "0001_squashed_0030_change_slug_field"),
    ]

    operations = [
        migrations.CreateModel(
            name="Sample",
            fields=[
                (
                    "id",
                    models.AutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                ("slug", SlugField(editable=True, max_length=100)),
                ("version", versionfield.VersionField(default=0)),
                ("name", models.CharField(max_length=100)),
                ("created", models.DateTimeField(auto_now_add=True)),
                ("modified", models.DateTimeField(auto_now=True)),
                ("description", models.TextField(blank=True)),
                (
                    "settings",
                    django.contrib.postgres.fields.jsonb.JSONField(default={}),
                ),
                (
                    "descriptor",
                    django.contrib.postgres.fields.jsonb.JSONField(default={}),
                ),
                ("collections", models.ManyToManyField(to="flow.Collection")),
                (
                    "contributor",
                    models.ForeignKey(
                        on_delete=django.db.models.deletion.PROTECT,
                        to=settings.AUTH_USER_MODEL,
                    ),
                ),
                ("data", models.ManyToManyField(to="flow.Data")),
                (
                    "descriptor_schema",
                    models.ForeignKey(
                        blank=True,
                        null=True,
                        on_delete=django.db.models.deletion.PROTECT,
                        to="flow.DescriptorSchema",
                    ),
                ),
                ("public_processes", models.ManyToManyField(to="flow.Process")),
            ],
            options={
                "default_permissions": (),
                "abstract": False,
                "permissions": (
                    ("view_sample", "Can view sample"),
                    ("edit_sample", "Can edit sample"),
                    ("share_sample", "Can share sample"),
                    ("download_sample", "Can download files from sample"),
                    ("add_sample", "Can add data objects to sample"),
                ),
            },
        ),
        migrations.AlterUniqueTogether(
            name="sample",
            unique_together=set([("slug", "version")]),
        ),
    ]