django.db.models.CharField

Here are the examples of the python api django.db.models.CharField taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: GAE-Bulk-Mailer
Source File: validation.py
View license
    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.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 2

Project: probr-core
Source File: models.py
View license
    def pre_save(self, model_instance, add):
        if add :
            value = str(uuid.uuid4())
            setattr(model_instance, self.attname, value)
            return value
        else:
            return super(models.CharField, self).pre_save(model_instance, add)

Example 3

Project: Django--an-app-at-a-time
Source File: models.py
View license
def add_spatial_version_related_fields(sender, **kwargs):
    """
    Adds fields after establishing a database connection to prevent database
    operations at compile time.
    """
    if connection_created.disconnect(add_spatial_version_related_fields, sender=DatabaseWrapper):
        spatial_version = connection.ops.spatial_version[0]
        if spatial_version >= 4:
            SpatialiteSpatialRefSys.add_to_class('srtext', models.CharField(max_length=2048))
            SpatialiteGeometryColumns.add_to_class('type', models.IntegerField(db_column='geometry_type'))
        else:
            SpatialiteGeometryColumns.add_to_class('type', models.CharField(max_length=30))

Example 4

Project: django-slim
Source File: fields.py
View license
    def formfield(self, **kwargs):
        """
        Returns best form field to represent this model field
        """
        defaults = {
            'form_class': LanguageField,
            'populate': self.populate,
        }
        defaults.update(kwargs)
        return super(models.CharField, self).formfield(**defaults)

Example 5

Project: django-slim
Source File: fields.py
View license
    def formfield(self, **kwargs):
        """
        Returns best form field to represent this model field
        """
        defaults = {
            'form_class': SimpleLanguageField,
            'populate': self.populate,
        }
        defaults.update(kwargs)
        return super(models.CharField, self).formfield(**defaults)

Example 6

Project: splunk-webframework
Source File: validation.py
View license
    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 7

Project: django-fancypages
Source File: base.py
View license
    def add_link_fields(cls):
        if not getattr(cls, 'link_field_name', None):
            cls.link_field_name = "link_url_%d"

        for idx in range(1, cls.num_links + 1):
            cls.add_to_class(
                cls.link_field_name % idx,
                models.CharField(_("Link URL %d" % idx), max_length=500,
                                 blank=True, null=True))

Example 8

View license
    def forwards(self, orm):
        db.create_table(u'content_featuretype', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('name', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('slug', self.gf('django.db.models.fields.SlugField')(unique=True, max_length=50)),
        ))
        db.send_create_signal(u'content', ['FeatureType'])
        # Adding field 'Content.feature_type'
        db.add_column(u'content_content', 'feature_type',
                      self.gf('django.db.models.fields.related.ForeignKey')(to=orm['content.FeatureType'], null=True, blank=True),
                      keep_default=False)
        db.alter_column('content_content', 'feature_type', models.CharField(max_length=255, null=True, blank=True))

Example 9

Project: transifex
Source File: 0001_initial.py
View license
    def forwards(self, orm):

        # Adding model 'Language'
        db.create_table('translations_language', (
            ('code_aliases', models.CharField(_('Code aliases'), default='', max_length=100, null=True)),
            ('code', models.CharField(_('Code'), max_length=50, unique=True)),
            ('description', models.CharField(_('Description'), max_length=255, blank=True)),
            ('pluralequation', models.CharField(_("Plural Equation"), max_length=255, blank=True)),
            ('nplurals', models.SmallIntegerField(_("Number of Plurals"), default=0)),
            ('specialchars', models.CharField(_("Special Chars"), max_length=255, blank=True)),
            ('id', models.AutoField(primary_key=True)),
            ('name', models.CharField(_('Name'), max_length=50, unique=True)),
        ))
        db.send_create_signal('languages', ['Language'])

Example 10

Project: nodewatcher
Source File: fields.py
View license
    def __init__(self, regpoint, enum_id, **kwargs):
        """
        Class constructor.
        """

        self.regpoint = regpoint
        self.enum_id = enum_id
        self._rp_choices = self.get_registered_choices().field_tuples()
        kwargs['base_field'] = models.CharField(max_length=50, choices=self._rp_choices)
        super(RegistryMultipleChoiceField, self).__init__(**kwargs)

Example 11

Project: django-mysql
Source File: aggregates.py
View license
    def __init__(self, expression, distinct=False, separator=None,
                 ordering=None, **extra):

        if 'output_field' not in extra:
            # This can/will be improved to SetTextField or ListTextField
            extra['output_field'] = CharField()

        super(GroupConcat, self).__init__(expression, **extra)

        self.distinct = distinct
        self.separator = separator

        if ordering not in ('asc', 'desc', None):
            raise ValueError(
                "'ordering' must be one of 'asc', 'desc', or None")
        self.ordering = ordering

Example 12

Project: django-mysql
Source File: functions.py
View license
    def __init__(self, num, expressions):
        value_exprs = []
        for v in expressions:
            if not hasattr(v, 'resolve_expression'):
                v = Value(v)
            value_exprs.append(v)

        super(ELT, self).__init__(num, *value_exprs, output_field=CharField())

Example 13

Project: django-mysql
Source File: functions.py
View license
    def __init__(self, expression, regex, replace):
        if not hasattr(regex, 'resolve_expression'):
            regex = Value(regex)

        if not hasattr(replace, 'resolve_expression'):
            replace = Value(replace)

        super(RegexpReplace, self).__init__(expression, regex, replace,
                                            output_field=CharField())

Example 14

Project: django-mysql
Source File: functions.py
View license
    def __init__(self, expression, regex):
        if not hasattr(regex, 'resolve_expression'):
            regex = Value(regex)

        super(RegexpSubstr, self).__init__(expression, regex,
                                           output_field=CharField())

Example 15

Project: canvas
Source File: 0042_fix_varchar_sizes.py
View license
    def forwards(self, orm):
        db.alter_column('canvas_content', 'remix_of_id', models.CharField(max_length=40, blank=True, null=True))
        db.alter_column('canvas_comment', 'parent_content_id', models.CharField(max_length=40))
        db.alter_column('canvas_comment', 'reply_content_id', models.CharField(max_length=40, blank=True, null=True))
        db.alter_column('canvas_contentsticker', 'content_id', models.CharField(max_length=40))
        db.alter_column('canvas_stashcontent', 'content_id', models.CharField(max_length=40))        

Example 16

Project: cgstudiomap
Source File: models.py
View license
def add_spatial_version_related_fields(sender, **kwargs):
    """
    Adds fields after establishing a database connection to prevent database
    operations at compile time.
    """
    if connection_created.disconnect(add_spatial_version_related_fields, sender=DatabaseWrapper):
        spatial_version = connection.ops.spatial_version[0]
        if spatial_version >= 4:
            SpatialiteSpatialRefSys.add_to_class('srtext', models.CharField(max_length=2048))
            SpatialiteGeometryColumns.add_to_class('type', models.IntegerField(db_column='geometry_type'))
        else:
            SpatialiteGeometryColumns.add_to_class('type', models.CharField(max_length=30))

Example 17

Project: decode-Django
Source File: validation.py
View license
    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.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: django-compositepks
Source File: validation.py
View license
    def validate_field(self, errors, opts, f):
        "Prior to MySQL 5.0.3, character fields could not exceed 255 characters"
        from django.db import models
        from django.db import connection
        db_version = connection.get_server_version()
        if db_version < (5, 0, 3) and isinstance(f, (models.CharField, models.CommaSeparatedIntegerField, models.SlugField)) and f.max_length > 255:
            errors.add(opts,
                '"%s": %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 %s).' % 
                (f.name, f.__class__.__name__, '.'.join([str(n) for n in db_version[:3]])))

Example 19

Project: django-cms
Source File: pluginmodel.py
View license
    def get_translatable_content(self):
        """
        Returns {field_name: field_contents} for translatable fields, where
        field_contents > ''
        """
        fields = (f for f in self._meta.fields
                  if isinstance(f, (models.CharField, models.TextField)) and
                     f.editable and not f.choices and
                     f.name not in self.translatable_content_excluded_fields)
        return dict(filter(itemgetter(1),
                           ((f.name, getattr(self, f.name)) for f in fields)))

Example 20

Project: django-cms
Source File: test_extensions.py
View license
    def get_page_extension_class(self):
        from django.db import models

        class TestPageExtension(PageExtension):
            content = models.CharField('Content', max_length=50)

            class Meta:
                abstract = True

        return TestPageExtension

Example 21

Project: django-cms
Source File: test_extensions.py
View license
    def get_title_extension_class(self):
        from django.db import models

        class TestTitleExtension(TitleExtension):
            content = models.CharField('Content', max_length=50)

            class Meta:
                abstract = True

        return TestTitleExtension

Example 22

Project: django-denorm
Source File: models.py
View license
    @denormalized(models.CharField, max_length=255)
    @depend_on_related('Member', foreign_key="author")
    def author_name(self):
        if self.author:
            return self.author.name
        else:
            return ''

Example 23

Project: django-leonardo
Source File: models.py
View license
    @classmethod
    def initialize_type(cls, TYPES=None):
        TYPES = TYPES or cls.DEFAULT_TYPES

        cls.FORMATTERS = dict((t[0], t[2]) for t in TYPES)
        cls.TYPE_CHOICES = [(t[0], t[1]) for t in TYPES]

        cls.add_to_class('type', models.CharField(_('type'), max_length=20,
                                                  choices=cls.TYPE_CHOICES,
                                                  default=cls.TYPE_CHOICES[0][0]))

        cls.add_to_class('data', models.TextField(_('data'), blank=True))

Example 24

Project: django-dbindexer
Source File: lookups.py
View license
    def __init__(self, *args, **kwargs):
        defaults = {'new_lookup': 'startswith',
                    'field_to_add': ListField(models.CharField(500),
                                              editable=False, null=True)
        }
        defaults.update(kwargs)
        ExtraFieldLookup.__init__(self, *args, **defaults)

Example 25

View license
    def forwards(self, orm):
        db.alter_column('canvas_content', 'remix_of_id', models.CharField(max_length=40, blank=True, null=True))
        db.alter_column('canvas_comment', 'parent_content_id', models.CharField(max_length=40))
        db.alter_column('canvas_comment', 'reply_content_id', models.CharField(max_length=40, blank=True, null=True))
        db.alter_column('canvas_contentsticker', 'content_id', models.CharField(max_length=40))
        db.alter_column('canvas_stashcontent', 'content_id', models.CharField(max_length=40))        

Example 26

View license
    def pre_save(self, model_instance, add):
        if add or not getattr(model_instance, self.attname):
            value = self._generate_uuid()
            setattr(model_instance, self.attname, value)
            return value
        else:
            return super(models.CharField, self).pre_save(model_instance, add)

Example 27

Project: django-accounting
Source File: fields.py
View license
    def pre_save(self, model_instance, add):
        if add or not getattr(model_instance, self.attname):
            value = self._generate_uuid()
            setattr(model_instance, self.attname, value)
            return value
        else:
            return super(models.CharField, self).pre_save(model_instance, add)

Example 28

Project: akvo-rsr
Source File: fields.py
View license
    def to_python(self, value):
        if isinstance(value, models.CharField):
            return value 
        if value is None:
            return ''
        return value

Example 29

Project: HealthStarter
Source File: models.py
View license
def add_spatial_version_related_fields(sender, **kwargs):
    """
    Adds fields after establishing a database connection to prevent database
    operations at compile time.
    """
    if connection_created.disconnect(add_spatial_version_related_fields, sender=DatabaseWrapper):
        spatial_version = connection.ops.spatial_version[0]
        if spatial_version >= 4:
            SpatialiteSpatialRefSys.add_to_class('srtext', models.CharField(max_length=2048))
            SpatialiteGeometryColumns.add_to_class('type', models.IntegerField(db_column='geometry_type'))
        else:
            SpatialiteGeometryColumns.add_to_class('type', models.CharField(max_length=30))

Example 30

Project: cms
Source File: models.py
View license
    def get_content(self, obj):
        """Returns the search text for the page."""
        content_obj = obj.content
        return u" ".join((
            super(PageSearchAdapter, self).get_content(obj),
            self.prepare_content(u" ".join(
                unicode(self._resolve_field(content_obj, field_name))
                for field_name in (
                    field.name for field
                    in content_obj._meta.fields
                    if isinstance(field, (models.CharField, models.TextField))
                )
            ))
        ))

Example 31

Project: feincms
Source File: contents.py
View license
    @classmethod
    def initialize_type(cls, TYPE_CHOICES=None):
        if TYPE_CHOICES is None:
            raise ImproperlyConfigured(
                'You have to set TYPE_CHOICES when'
                ' creating a %s' % cls.__name__)

        cls.add_to_class(
            'type',
            models.CharField(
                _('type'),
                max_length=20,
                choices=TYPE_CHOICES,
                default=TYPE_CHOICES[0][0],
            )
        )

Example 32

Project: django-scrape
Source File: items.py
View license
def get_field_query(item, field, value, pipeline, spider, use_null=False):
    if value in ('', None, []):
        if use_null:
            if isinstance(field, (django_models.CharField, django_models.TextField)):
                return ('', '')
            else:
                return ('__isnull', True)
        else:
            return None
    value = get_field_value(item, field, value, pipeline, spider)
    if isinstance(field, AddressField):
        return ('', value)
    elif isinstance(field, ManyToManyField):
        return ('__contains', value)
    elif isinstance(field, FileField):
        return ('__contains', os.path.basename(value))
    return ('', value)

Example 33

Project: Geotrek-admin
Source File: parsers.py
View license
    def set_value(self, dst, src, val):
        field = self.model._meta.get_field_by_name(dst)[0]
        if val is None and not field.null:
            if field.blank and (isinstance(field, models.CharField) or isinstance(field, models.TextField)):
                val = u""
            else:
                raise RowImportError(_(u"Null value not allowed for field '{src}'".format(src=src)))
        if val == u"" and not field.blank:
            raise RowImportError(_(u"Blank value not allowed for field '{src}'".format(src=src)))
        setattr(self.obj, dst, val)

Example 34

Project: golismero
Source File: validation.py
View license
    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 35

Project: django-databrowse
Source File: datastructures.py
View license
    def test_choices(self):
        em = EasyModel(django_databrowse.site, SomeModel)
        field = EasyField(
            em,
            models.CharField(max_length=2,
                             choices=(("a", "azerty"),("q","querty"))
                             )
            )
        self.assertEqual(len([f for f in field.choices()]), 2)

Example 36

Project: django-databrowse
Source File: datastructures.py
View license
    def test_urls(self):
        em = EasyModel(django_databrowse.site, SomeModel)
        em.site.root_url = "root/"
        field = EasyField(
            em,
            models.CharField(max_length=2,
                             choices=(("a", "azerty"),("q","querty")),
                             name="hello"
                             )
            )
        self.assertEqual(field.url(),
                         u'root/django_databrowse/somemodel/hello/')

        em = EasyModel(django_databrowse.site, SomeInheritedModel)
        field = EasyField(em, models.ForeignKey(SomeModel))
        self.assertEqual(field.url(),
                         u'root/django_databrowse/someinheritedmodel/')

Example 37

Project: django-databrowse
Source File: datastructures.py
View license
    def test_repr(self):
        em = EasyModel(django_databrowse.site, SomeModel)
        field = models.CharField(max_length=2, name="Hello")
        value, label = "a", "azerty"
        ec = EasyChoice(em, field, value, label)
        self.assertEqual(ec.__repr__(), "<EasyChoice for SomeModel.Hello>")

Example 38

Project: feedsanitizer
Source File: lookups.py
View license
    def __init__(self, *args, **kwargs):
        defaults = {'new_lookup': 'startswith',
                    'field_to_add': ListField(models.CharField(500),
                                              editable=False, null=True)
        }
        defaults.update(kwargs)
        ExtraFieldLookup.__init__(self, *args, **defaults)

Example 39

Project: hunch-sample-app
Source File: filter.py
View license
    def __init__(self, model, field_name, regex):
        self.regex = re.compile(regex.pattern, re.S | re.U | (regex.flags & re.I))
        lookup_type = self.regex.flags & re.I and 'iregex' or 'regex'
        super(ExtraFieldLookup, self).__init__(model, field_name,
            lookup_type, ListField(models.CharField(max_length=256),
            editable=False, null=True))

Example 40

Project: feincms-articles
Source File: content.py
View license
    @classmethod
    def initialize_type(cls, LAYOUT_CHOICES=None):

        cls.add_to_class('layout', models.CharField(_('Layout'),
                                                    max_length=10, choices=LAYOUT_CHOICES,
                                                    default=LAYOUT_CHOICES[0][0]))

        class ArticleCategoryListForm(ItemEditorForm):
            layout = forms.ChoiceField(choices=LAYOUT_CHOICES,
                                       initial=LAYOUT_CHOICES[0][0], label=_('Layout'),
                                       widget=AdminRadioSelect(attrs={'class': 'radiolist'}))

        cls.feincms_item_editor_form = ArticleCategoryListForm
        cls.form = ArticleCategoryListForm

Example 41

Project: django-markupfield
Source File: fields.py
View license
    def contribute_to_class(self, cls, name):
        if self.rendered_field and not cls._meta.abstract:
            choices = zip([''] + self.markup_choices_list,
                          ['--'] + self.markup_choices_title)
            markup_type_field = models.CharField(
                max_length=30,
                choices=choices, default=self.default_markup_type,
                editable=self.markup_type_editable,
                blank=False if self.default_markup_type else True,
                null=False if self.default_markup_type else True,
            )
            rendered_field = models.TextField(editable=False, null=self.null)
            markup_type_field.creation_counter = self.creation_counter + 1
            rendered_field.creation_counter = self.creation_counter + 2
            cls.add_to_class(_markup_type_field_name(name), markup_type_field)
            cls.add_to_class(_rendered_field_name(name), rendered_field)
        super(MarkupField, self).contribute_to_class(cls, name)

        setattr(cls, self.name, MarkupDescriptor(self))

Example 42

Project: keops
Source File: models.py
View license
    def to_python(self, value):
        if isinstance(value, models.CharField):
            return value
        if value == None:
            return ""
        else:
            return value

Example 43

Project: keops
Source File: models.py
View license
    def to_python(self, value):
        if isinstance(value, models.CharField):
            return value
        if value == None:
            return ""
        else:
            return value

Example 44

Project: django-any
Source File: models.py
View license
@any_field.register(models.CharField)
def any_char_field(field, **kwargs):
    """
    Return random value for CharField

    >>> result = any_field(models.CharField(max_length=10))
    >>> type(result)
    <type 'str'>
    """
    min_length = kwargs.get('min_length', 1)
    max_length = kwargs.get('max_length', field.max_length)
    return xunit.any_string(min_length=min_length, max_length=max_length)

Example 45

Project: django-any
Source File: field_attr_choices.py
View license
    def test_choices_named_groups_support(self):
        """
        Group names completely ignored
        """
        MEDIA_CHOICES = (
            ('Audio', (
                    ('vinyl', 'Vinyl'),
                    ('cd', 'CD'),
                    )),
            ('Video', (
                    ('vhs', 'VHS Tape'),
                    ('dvd', 'DVD'),
                    )),
            ('unknown', 'Unknown'))
        media = models.CharField(max_length=25, choices=MEDIA_CHOICES)

        result = any_field(media)

        self.assertTrue(result in ['vinyl', 'cd', 'vhs', 'dvd', 'unknown'])

Example 46

Project: django-any
Source File: test_custom_seed.py
View license
    @without_random_seed
    @with_seed(1)
    def test_deterministic_string(self):
        media = models.CharField(max_length=25)
        result = any_field(media)
        self.assertEqual('SNnz', result)

Example 47

Project: django-any
Source File: test_custom_seed.py
View license
    @without_random_seed
    @with_seed(1)
    def test_deterministic_string(self):
        media = models.CharField(max_length=25)
        result = any_field(media)
        self.assertEqual('SNnz', result)

Example 48

Project: localwiki-backend-server
Source File: tests.py
View license
    def test_can_handle_any_field(self):
        """
        Out of the box, the registry should offer diff utils for any field.
        """
        r = self.registry
        field_types = [db.models.CharField, db.models.TextField,
                       db.models.BooleanField]
        for t in field_types:
            d = r.get_diff_util(t)
            self.assertTrue(issubclass(d, BaseFieldDiff))

Example 49

Project: localwiki-backend-server
Source File: tests.py
View license
    def test_register_field(self):
        """
        If we register a fielddiff for a model, we should get that and not
        BaseFieldDiff.
        """
        self.registry.register(db.models.CharField, Diff_M1FieldDiff)
        self.failUnlessEqual(self.registry.get_diff_util(db.models.CharField),
                             Diff_M1FieldDiff)

Example 50

Project: geraldo
Source File: validation.py
View license
    def validate_field(self, errors, opts, f):
        "Prior to MySQL 5.0.3, character fields could not exceed 255 characters"
        from django.db import models
        from django.db import connection
        db_version = connection.get_server_version()
        if db_version < (5, 0, 3) and isinstance(f, (models.CharField, models.CommaSeparatedIntegerField, models.SlugField)) and f.max_length > 255:
            errors.add(opts,
                '"%s": %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 %s).' % 
                (f.name, f.__class__.__name__, '.'.join([str(n) for n in db_version[:3]])))