Python django.db.models.SlugField() Examples

The following are code examples for showing how to use django.db.models.SlugField(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: django-reading-list   Author: simonv3   File: slugify.py    MIT License 6 votes vote down vote up
def _get_fields_and_data(model):
    opts = model._meta
    slug_fields = []
    for f in opts.fields:
        if isinstance(f, models.SlugField):
            if not f.prepopulate_from:
                raise SlugNotCorrectlyPrePopulated(
                    "Slug for %s is not prepopulated" % f.name
                )

            prepop = []
            for n in f.prepopulate_from:
                if not hasattr(model, n):
                    raise SlugNotCorrectlyPrePopulated(
                        "Slug for %s is to be prepopulated from %s, yet %s." +
                        "%s does not exist" % (f.name, n, type(model), n))
                else:
                    prepop.append(getattr(model, n))
            slug_fields.append([f, "_".join(prepop)])
    return slug_fields 
Example 2
Project: forum-xblock   Author: DANCEcollaborative   File: validation.py    MIT License 6 votes vote down vote up
def validate_field(self, errors, opts, f):
        """
        There are some field length restrictions for MySQL:

        - Prior to version 5.0.3, character fields could not exceed 255
          characters in length.
        - No character (varchar) fields can have a length exceeding 255
          characters if they have a unique index on them.
        """
        from django.db import models
        db_version = self.connection.get_server_version()
        varchar_fields = (models.CharField, models.CommaSeparatedIntegerField,
                models.SlugField)
        if isinstance(f, varchar_fields) and f.max_length > 255:
            if db_version < (5, 0, 3):
                msg = '"%(name)s": %(cls)s cannot have a "max_length" greater than 255 when you are using a version of MySQL prior to 5.0.3 (you are using %(version)s).'
            elif f.unique == True:
                msg = '"%(name)s": %(cls)s cannot have a "max_length" greater than 255 when using "unique=True".'
            else:
                msg = None

            if msg:
                errors.add(opts, msg % {'name': f.name, 'cls': f.__class__.__name__, 'version': '.'.join([str(n) for n in db_version[:3]])}) 
Example 3
Project: Kiwi-tcms   Author: Coder-AMiT   File: __init__.py    GNU General Public License v2.0 6 votes vote down vote up
def clean(self):
        strip_types = (models.CharField,
                       models.TextField,
                       models.URLField,
                       models.EmailField,
                       models.IPAddressField,
                       models.GenericIPAddressField,
                       models.SlugField)

        for field in self._meta.fields:
            # TODO: hardcode 'notes' here
            if not (field.name is 'notes') and isinstance(field, strip_types):
                value = getattr(self, field.name)
                if value:
                    setattr(self, field.name,
                            value.replace('\t', ' ').replace('\n', ' ').replace('\r', ' ')) 
Example 4
Project: django-modeltrans   Author: zostera   File: test_querysets.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_non_id_pk(self):
        """This model doesn't have a id column"""

        class NonIdPrimaryKeyModel(models.Model):
            slug = models.SlugField(primary_key=True)
            title = models.CharField(max_length=100)
            i18n = TranslationField(fields=("title",))

            class Meta:
                app_label = "tests"

        translate_model(NonIdPrimaryKeyModel)

        with CreateTestModel(NonIdPrimaryKeyModel):
            field, lookup_type = NonIdPrimaryKeyModel.objects.all()._get_field("pk")

            self.assertEqual(field.name, "slug") 
Example 5
Project: omni-forms   Author: omni-digital   File: models.py    MIT License 5 votes vote down vote up
def get_concrete_class_for_model_field(cls, model_field):
        """
        Method for getting a concrete model class to represent the type of form field required

        :param model_field: Model Field instance
        :return: OmniField subclass
        """
        field_mapping = {
            models.CharField: OmniCharField,
            models.TextField: OmniCharField,
            models.BooleanField: OmniBooleanField,
            models.NullBooleanField: OmniBooleanField,
            models.DateField: OmniDateField,
            models.DateTimeField: OmniDateTimeField,
            models.DecimalField: OmniDecimalField,
            models.EmailField: OmniEmailField,
            models.FloatField: OmniFloatField,
            models.IntegerField: OmniIntegerField,
            models.BigIntegerField: OmniIntegerField,
            models.PositiveIntegerField: OmniIntegerField,
            models.PositiveSmallIntegerField: OmniIntegerField,
            models.SmallIntegerField: OmniIntegerField,
            models.CommaSeparatedIntegerField: OmniCharField,
            models.TimeField: OmniTimeField,
            models.URLField: OmniUrlField,
            models.ForeignKey: OmniForeignKeyField,
            models.ManyToManyField: OmniManyToManyField,
            models.SlugField: OmniSlugField,
            models.FileField: OmniFileField,
            models.ImageField: OmniImageField,
            models.DurationField: OmniDurationField,
            models.GenericIPAddressField: OmniGenericIPAddressField
        }
        field_mapping.update(cls.get_custom_field_mapping())
        return field_mapping.get(model_field.__class__) 
Example 6
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_get_concrete_class_for_model_field(self):
        """
        The get_concrete_class_for_model_field method should return the correct OmniField subclass
        """
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.CharField()), OmniCharField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.NullBooleanField()), OmniBooleanField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.BooleanField()), OmniBooleanField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.DateTimeField()), OmniDateTimeField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.DecimalField()), OmniDecimalField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.EmailField()), OmniEmailField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.FloatField()), OmniFloatField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.IntegerField()), OmniIntegerField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.BigIntegerField()), OmniIntegerField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.PositiveIntegerField()), OmniIntegerField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.SmallIntegerField()), OmniIntegerField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.TimeField()), OmniTimeField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.URLField()), OmniUrlField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.SlugField()), OmniSlugField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.FileField()), OmniFileField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.ImageField()), OmniImageField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.DurationField()), OmniDurationField)
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.GenericIPAddressField()),
            OmniGenericIPAddressField
        )
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.CommaSeparatedIntegerField()),
            OmniCharField
        )
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.PositiveSmallIntegerField()),
            OmniIntegerField
        )
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.ForeignKey(DummyModel2)),
            OmniForeignKeyField
        )
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.ManyToManyField(DummyModel2)),
            OmniManyToManyField
        ) 
Example 7
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_initial(self):
        """
        The model should have an initial field
        """
        field = OmniSlugField._meta.get_field('initial_data')
        self.assertIsInstance(field, models.SlugField)
        self.assertTrue(field.blank)
        self.assertTrue(field.null) 
Example 8
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_field_class(self):
        """
        The model should define the correct field class
        """
        self.assertEqual(OmniSlugField.FIELD_CLASS, 'django.forms.SlugField') 
Example 9
Project: TESTGIT   Author: B-ROY   File: validation.py    Apache License 2.0 5 votes vote down vote up
def validate_field(self, errors, opts, f):
        """
        MySQL has the following field length restriction:
        No character (varchar) fields can have a length exceeding 255
        characters if they have a unique index on them.
        """
        from django.db import models
        varchar_fields = (models.CharField, models.CommaSeparatedIntegerField,
                models.SlugField)
        if (isinstance(f, varchar_fields) and f.unique
                and (f.max_length is None or int(f.max_length) > 255)):
            msg = '"%(name)s": %(cls)s cannot have a "max_length" greater than 255 when using "unique=True".'
            errors.add(opts, msg % {'name': f.name, 'cls': f.__class__.__name__}) 
Example 10
Project: Fun5G   Author: OpenWinCon   File: validation.py    Apache License 2.0 5 votes vote down vote up
def validate_field(self, errors, opts, f):
            """
            MySQL has the following field length restriction:
            No character (varchar) fields can have a length exceeding 255
            characters if they have a unique index on them.
            """
            varchar_fields = (models.CharField,
                              models.CommaSeparatedIntegerField,
                              models.SlugField)
            if isinstance(f, varchar_fields) and f.max_length > 255 and f.unique:
                msg = ('"%(name)s": %(cls)s cannot have a "max_length" greater '
                       'than 255 when using "unique=True".')
                errors.add(opts, msg % {'name': f.name,
                                        'cls': f.__class__.__name__}) 
Example 11
Project: stack-recon   Author: CharlesMcKinnis   File: validation.py    Apache License 2.0 5 votes vote down vote up
def validate_field(self, errors, opts, f):
            """
            MySQL has the following field length restriction:
            No character (varchar) fields can have a length exceeding 255
            characters if they have a unique index on them.
            """
            varchar_fields = (models.CharField,
                              models.CommaSeparatedIntegerField,
                              models.SlugField)
            if isinstance(f, varchar_fields) and f.max_length > 255 and f.unique:
                msg = ('"%(name)s": %(cls)s cannot have a "max_length" greater '
                       'than 255 when using "unique=True".')
                errors.add(opts, msg % {'name': f.name,
                                        'cls': f.__class__.__name__}) 
Example 12
Project: driving-reserve   Author: liukaijv   File: test_filterset.py    MIT License 5 votes vote down vote up
def test_expected_db_fields_get_filters(self):
        to_check = [
            models.BooleanField,
            models.CharField,
            models.CommaSeparatedIntegerField,
            models.DateField,
            models.DateTimeField,
            models.DecimalField,
            models.EmailField,
            models.FilePathField,
            models.FloatField,
            models.IntegerField,
            models.IPAddressField,
            models.NullBooleanField,
            models.PositiveIntegerField,
            models.PositiveSmallIntegerField,
            models.SlugField,
            models.SmallIntegerField,
            models.TextField,
            models.TimeField,
            models.URLField,
            models.ForeignKey,
            models.OneToOneField,
            models.ManyToManyField,
        ]
        msg = "%s expected to be found in FILTER_FOR_DBFIELD_DEFAULTS"

        for m in to_check:
            self.assertIn(m, FILTER_FOR_DBFIELD_DEFAULTS, msg % m.__name__) 
Example 13
Project: luscan-devel   Author: blackye   File: validation.py    GNU General Public License v2.0 5 votes vote down vote up
def validate_field(self, errors, opts, f):
        """
        MySQL has the following field length restriction:
        No character (varchar) fields can have a length exceeding 255
        characters if they have a unique index on them.
        """
        from django.db import models
        varchar_fields = (models.CharField, models.CommaSeparatedIntegerField,
                models.SlugField)
        if (isinstance(f, varchar_fields) and f.unique
                and (f.max_length is None or int(f.max_length) > 255)):
            msg = '"%(name)s": %(cls)s cannot have a "max_length" greater than 255 when using "unique=True".'
            errors.add(opts, msg % {'name': f.name, 'cls': f.__class__.__name__}) 
Example 14
Project: global-ssh-server   Author: nthiep   File: validation.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def validate_field(self, errors, opts, f):
        """
        MySQL has the following field length restriction:
        No character (varchar) fields can have a length exceeding 255
        characters if they have a unique index on them.
        """
        from django.db import models
        varchar_fields = (models.CharField, models.CommaSeparatedIntegerField,
                models.SlugField)
        if (isinstance(f, varchar_fields) and f.unique
                and (f.max_length is None or int(f.max_length) > 255)):
            msg = '"%(name)s": %(cls)s cannot have a "max_length" greater than 255 when using "unique=True".'
            errors.add(opts, msg % {'name': f.name, 'cls': f.__class__.__name__}) 
Example 15
Project: MONITT   Author: meeeejin   File: validation.py    MIT License 5 votes vote down vote up
def validate_field(self, errors, opts, f):
        """
        MySQL has the following field length restriction:
        No character (varchar) fields can have a length exceeding 255
        characters if they have a unique index on them.
        """
        from django.db import models
        varchar_fields = (models.CharField, models.CommaSeparatedIntegerField,
                models.SlugField)
        if (isinstance(f, varchar_fields) and f.unique
                and (f.max_length is None or int(f.max_length) > 255)):
            msg = '"%(name)s": %(cls)s cannot have a "max_length" greater than 255 when using "unique=True".'
            errors.add(opts, msg % {'name': f.name, 'cls': f.__class__.__name__}) 
Example 16
Project: graphene-django   Author: graphql-python   File: test_converter.py    MIT License 5 votes vote down vote up
def test_should_slug_convert_string():
    assert_conversion(models.SlugField, graphene.String) 
Example 17
Project: importacsv   Author: rasertux   File: validation.py    GNU General Public License v3.0 5 votes vote down vote up
def validate_field(self, errors, opts, f):
            """
            MySQL has the following field length restriction:
            No character (varchar) fields can have a length exceeding 255
            characters if they have a unique index on them.
            """
            varchar_fields = (models.CharField,
                              models.CommaSeparatedIntegerField,
                              models.SlugField)
            if isinstance(f, varchar_fields) and f.max_length > 255 and f.unique:
                msg = ('"%(name)s": %(cls)s cannot have a "max_length" greater '
                       'than 255 when using "unique=True".')
                errors.add(opts, msg % {'name': f.name,
                                        'cls': f.__class__.__name__}) 
Example 18
Project: taiga-back-   Author: andyzsf   File: serializers.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def get_field(self, model_field):
        """
        Creates a default instance of a basic non-relational field.
        """
        kwargs = {}

        if model_field.null or model_field.blank:
            kwargs["required"] = False

        if isinstance(model_field, models.AutoField) or not model_field.editable:
            kwargs["read_only"] = True

        if model_field.has_default():
            kwargs["default"] = model_field.get_default()

        if issubclass(model_field.__class__, models.TextField):
            kwargs["widget"] = widgets.Textarea

        if model_field.verbose_name is not None:
            kwargs["label"] = model_field.verbose_name

        if model_field.help_text is not None:
            kwargs["help_text"] = model_field.help_text

        # TODO: TypedChoiceField?
        if model_field.flatchoices:  # This ModelField contains choices
            kwargs["choices"] = model_field.flatchoices
            if model_field.null:
                kwargs["empty"] = None
            return ChoiceField(**kwargs)

        # put this below the ChoiceField because min_value isn't a valid initializer
        if issubclass(model_field.__class__, models.PositiveIntegerField) or\
                issubclass(model_field.__class__, models.PositiveSmallIntegerField):
            kwargs["min_value"] = 0

        attribute_dict = {
            models.CharField: ["max_length"],
            models.CommaSeparatedIntegerField: ["max_length"],
            models.DecimalField: ["max_digits", "decimal_places"],
            models.EmailField: ["max_length"],
            models.FileField: ["max_length"],
            models.ImageField: ["max_length"],
            models.SlugField: ["max_length"],
            models.URLField: ["max_length"],
        }

        if model_field.__class__ in attribute_dict:
            attributes = attribute_dict[model_field.__class__]
            for attribute in attributes:
                kwargs.update({attribute: getattr(model_field, attribute)})

        if model_field.name in self.opts.i18n_fields:
            kwargs["i18n"] = True

        try:
            return self.field_mapping[model_field.__class__](**kwargs)
        except KeyError:
            return ModelField(model_field=model_field, **kwargs) 
Example 19
Project: docker-django-polymer-starter-kit   Author: JTarball   File: models_backup.py    ISC License 4 votes vote down vote up
def save(self, *args, **kwargs):
        print self.child.all()
        if self.child.all() is None: super(SubCategory, self).save(*args, **kwargs)
        children = [child.id for child in self.child.all()]
        print children
        if self.parent is not None:
            if self.parent.id in children:
                print "EROORRORO!"
                ValidationError('You have not met a constraint!')
            else:
                super(SubCategory, self).save(*args, **kwargs)
        else:
            super(SubCategory, self).save(*args, **kwargs)







#/language/category/subcategory/...../post_slug

# # Create Dynamic URL tree
# class Node(models.Model):
#     name = models.CharField(max_length=50)
#     slug = models.SlugField(max_length=50, unique=True, help_text='Used for URL. ')  
#     # where does the dynamic tree start from   
#     language = models.ForeignKey(Language, related_name='root', null=True, blank=True)
#     category = models.ForeignKey(Category, related_name='root', null=True, blank=True)
#     subcategory = models.ForeignKey(SubCategory, related_name='root', null=True, blank=True)

#     parent = models.ForeignKey('self', related_name='other_subcategory', null=True, blank=True)
#     child = models.ManyToManyField('self', null = True, blank = True )
    
#     def __unicode__(self):
#         return self.name                        # return a string representation of our model

#     def save(self, *args, **kwargs):
#         if self.child.all() is None: super(Node, self).save(*args, **kwargs)
#         children = [child.id for child in self.child.all()]
#         print children
#         if self.parent is not None:
#             if self.parent.id in children:
#                 ValidationError('You have not met a constraint!')
#             else:
#                 super(Node, self).save(*args, **kwargs)
#         else:
#             super(Node, self).save(*args, **kwargs) 
Example 20
Project: docker-django-polymer-starter-kit   Author: JTarball   File: models.py    ISC License 4 votes vote down vote up
def save(self, *args, **kwargs):
        print self.child.all()
        if self.child.all() is None: super(SubCategory, self).save(*args, **kwargs)
        children = [child.id for child in self.child.all()]
        print children
        if self.parent is not None:
            if self.parent.id in children:
                print "EROORRORO!"
                ValidationError('You have not met a constraint!')
            else:
                super(SubCategory, self).save(*args, **kwargs)
        else:
            super(SubCategory, self).save(*args, **kwargs)







#/language/category/subcategory/...../post_slug

# # Create Dynamic URL tree
# class Node(models.Model):
#     name = models.CharField(max_length=50)
#     slug = models.SlugField(max_length=50, unique=True, help_text='Used for URL. ')  
#     # where does the dynamic tree start from   
#     language = models.ForeignKey(Language, related_name='root', null=True, blank=True)
#     category = models.ForeignKey(Category, related_name='root', null=True, blank=True)
#     subcategory = models.ForeignKey(SubCategory, related_name='root', null=True, blank=True)

#     parent = models.ForeignKey('self', related_name='other_subcategory', null=True, blank=True)
#     child = models.ManyToManyField('self', null = True, blank = True )
    
#     def __unicode__(self):
#         return self.name                        # return a string representation of our model

#     def save(self, *args, **kwargs):
#         if self.child.all() is None: super(Node, self).save(*args, **kwargs)
#         children = [child.id for child in self.child.all()]
#         print children
#         if self.parent is not None:
#             if self.parent.id in children:
#                 ValidationError('You have not met a constraint!')
#             else:
#                 super(Node, self).save(*args, **kwargs)
#         else:
#             super(Node, self).save(*args, **kwargs) 
Example 21
Project: docker-django-polymer-starter-kit   Author: JTarball   File: models_backup.py    ISC License 4 votes vote down vote up
def save(self, *args, **kwargs):
        print self.child.all()
        if self.child.all() is None: super(SubCategory, self).save(*args, **kwargs)
        children = [child.id for child in self.child.all()]
        print children
        if self.parent is not None:
            if self.parent.id in children:
                print "EROORRORO!"
                ValidationError('You have not met a constraint!')
            else:
                super(SubCategory, self).save(*args, **kwargs)
        else:
            super(SubCategory, self).save(*args, **kwargs)







#/language/category/subcategory/...../post_slug

# # Create Dynamic URL tree
# class Node(models.Model):
#     name = models.CharField(max_length=50)
#     slug = models.SlugField(max_length=50, unique=True, help_text='Used for URL. ')  
#     # where does the dynamic tree start from   
#     language = models.ForeignKey(Language, related_name='root', null=True, blank=True)
#     category = models.ForeignKey(Category, related_name='root', null=True, blank=True)
#     subcategory = models.ForeignKey(SubCategory, related_name='root', null=True, blank=True)

#     parent = models.ForeignKey('self', related_name='other_subcategory', null=True, blank=True)
#     child = models.ManyToManyField('self', null = True, blank = True )
    
#     def __unicode__(self):
#         return self.name                        # return a string representation of our model

#     def save(self, *args, **kwargs):
#         if self.child.all() is None: super(Node, self).save(*args, **kwargs)
#         children = [child.id for child in self.child.all()]
#         print children
#         if self.parent is not None:
#             if self.parent.id in children:
#                 ValidationError('You have not met a constraint!')
#             else:
#                 super(Node, self).save(*args, **kwargs)
#         else:
#             super(Node, self).save(*args, **kwargs) 
Example 22
Project: docker-django-polymer-starter-kit   Author: JTarball   File: models.py    ISC License 4 votes vote down vote up
def save(self, *args, **kwargs):
        print self.child.all()
        if self.child.all() is None: super(SubCategory, self).save(*args, **kwargs)
        children = [child.id for child in self.child.all()]
        print children
        if self.parent is not None:
            if self.parent.id in children:
                print "EROORRORO!"
                ValidationError('You have not met a constraint!')
            else:
                super(SubCategory, self).save(*args, **kwargs)
        else:
            super(SubCategory, self).save(*args, **kwargs)







#/language/category/subcategory/...../post_slug

# # Create Dynamic URL tree
# class Node(models.Model):
#     name = models.CharField(max_length=50)
#     slug = models.SlugField(max_length=50, unique=True, help_text='Used for URL. ')  
#     # where does the dynamic tree start from   
#     language = models.ForeignKey(Language, related_name='root', null=True, blank=True)
#     category = models.ForeignKey(Category, related_name='root', null=True, blank=True)
#     subcategory = models.ForeignKey(SubCategory, related_name='root', null=True, blank=True)

#     parent = models.ForeignKey('self', related_name='other_subcategory', null=True, blank=True)
#     child = models.ManyToManyField('self', null = True, blank = True )
    
#     def __unicode__(self):
#         return self.name                        # return a string representation of our model

#     def save(self, *args, **kwargs):
#         if self.child.all() is None: super(Node, self).save(*args, **kwargs)
#         children = [child.id for child in self.child.all()]
#         print children
#         if self.parent is not None:
#             if self.parent.id in children:
#                 ValidationError('You have not met a constraint!')
#             else:
#                 super(Node, self).save(*args, **kwargs)
#         else:
#             super(Node, self).save(*args, **kwargs) 
Example 23
Project: django-clone   Author: jackton1   File: clone.py    MIT License 4 votes vote down vote up
def _create_copy_of_instance(cls, instance):
        defaults = {}
        fields = []

        for f in instance._meta.concrete_fields:
            valid = False
            if not f.primary_key:
                if cls._clone_model_fields:
                    valid = f.name in cls._clone_model_fields
                elif cls._clone_excluded_model_fields:
                    valid = f.name not in cls._clone_excluded_model_fields
                else:
                    valid = True

            if valid:
                fields.append(f)

        unique_field_names = cls.unpack_unique_together(
            opts=instance._meta,
            only_fields=[f.attname for f in fields],
        )

        unique_fields = [
            f.name for f in fields
            if not f.auto_created and (f.unique or f.name in unique_field_names)
        ]

        for f in fields:
            if all([
                not f.auto_created,
                f.concrete,
                f.editable,
                f not in instance._meta.related_objects,
                f not in instance._meta.many_to_many,
            ]):
                value = getattr(instance, f.attname, f.get_default())
                if f.attname in unique_fields and isinstance(f, models.CharField):
                    value = clean_value(value, cls.UNIQUE_DUPLICATE_SUFFIX)
                    if cls.USE_UNIQUE_DUPLICATE_SUFFIX:
                        value = get_unique_value(
                            instance,
                            f.attname,
                            value,
                            cls.UNIQUE_DUPLICATE_SUFFIX,
                            f.max_length,
                            cls.MAX_UNIQUE_DUPLICATE_QUERY_ATTEMPTS
                        )
                    if isinstance(f, SlugField):
                        value = slugify(value)
                defaults[f.attname] = value

        return cls(**defaults) 
Example 24
Project: populous   Author: peopledoc   File: populous.py    MIT License 4 votes vote down vote up
def fields_mapping(self):
        params = [
            (models.AutoField, self.skip),
            (models.BigIntegerField, self.handle_integer),
            (models.BinaryField, None),
            (models.BooleanField, self.handle_boolean),
            (models.CommaSeparatedIntegerField, None),
            (models.DateField, partial(self.handle_datetime, date=True)),
            (models.DateTimeField, self.handle_datetime),
            (models.DecimalField, None),
            (models.DurationField, None),
            (models.EmailField, partial(self.handle_text, generator='Email')),
            (models.FileField, None),
            (models.FilePathField, None),
            (models.FloatField, None),
            (models.ImageField, None),
            (models.IntegerField, self.handle_integer),
            (models.GenericIPAddressField, self.handle_ip),
            (models.NullBooleanField, self.handle_boolean),
            (models.PositiveIntegerField, self.handle_integer),
            (models.PositiveSmallIntegerField, self.handle_integer),
            (models.SlugField, None),
            (models.SmallIntegerField, self.handle_integer),
            (models.TextField, self.handle_text),
            (models.TimeField, None),
            (models.URLField, partial(self.handle_text, generator='URL')),
            (models.UUIDField, self.handle_uuid),
            (models.CharField, self.handle_text),
            (models.ForeignKey, None),
            (models.OneToOneField, None),
            (models.ManyToManyField, self.skip)
        ]

        try:
            # Django < 1.9
            params.append((models.IPAddressField, self.handle_ip))
        except AttributeError:
            pass

        try:
            # Django >= 1.10
            params.append((models.BigAutoField, self.skip))
        except AttributeError:
            pass

        return params