Python django.db.models.TextField() Examples

The following are code examples for showing how to use django.db.models.TextField(). 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: openhatch   Author: campbe13   File: 0001_initial.py    GNU Affero General Public License v3.0 10 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'Project'
        db.create_table('search_project', (
            ('id', models.AutoField(primary_key=True)),
            ('language', models.CharField(max_length=200)),
            ('name', models.CharField(max_length=200)),
        ))
        db.send_create_signal('search', ['Project'])
        
        # Adding model 'Bug'
        db.create_table('search_bug', (
            ('project', models.ForeignKey(orm.Project)),
            ('status', models.CharField(max_length=200)),
            ('description', models.TextField()),
            ('id', models.AutoField(primary_key=True)),
            ('title', models.CharField(max_length=200)),
        ))
        db.send_create_signal('search', ['Bug']) 
Example 2
Project: eventsourcing   Author: johnbywater   File: test_process_with_django.py    BSD 3-Clause "New" or "Revised" License 8 votes vote down vote up
def define_projection_record_class(self):
        class ProjectionRecord(models.Model):
            uid = models.BigAutoField(primary_key=True)

            # Sequence ID (e.g. an entity or aggregate ID).
            projection_id = models.UUIDField()

            # State of the item (serialized dict, possibly encrypted).
            state = models.TextField()

            class Meta:
                db_table = "projections"
                app_label = "projections"
                managed = False

        self.projection_record_class = ProjectionRecord 
Example 3
Project: django-atom   Author: ad-m   File: generate_factory.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_creator_for_field(self, name, field, model):
        if isinstance(field, models.AutoField):
            return False
        if isinstance(field, models.ForeignKey):
            return 'factory.SubFactory("{}")'.format(self.get_subfactory_path(field.related_model))
        if isinstance(field, models.CharField):
            return 'factory.Sequence("{0}-{1}-{{0}}".format)'.format(self.safe_name(model.__name__), self.safe_name(name))
        if isinstance(field, models.TextField):
            return "factory.fuzzy.FuzzyText()"
        if isinstance(field, (models.BooleanField, models.NullBooleanField)):
            return "factory.Sequence(lambda n: n % 2 == 0)"
        if isinstance(field, (models.IntegerField, models.SmallIntegerField)):
            return "factory.Sequence(lambda n: n)"
        if isinstance(field, (models.DateTimeField)):
            if field.__class__.__name__ in ['AutoLastModifiedField', 'AutoCreatedField']:  # django-model-utils fields
                return False
            return "factory.fuzzy.FuzzyNaiveDateTime(datetime.datetime(2008, 1, 1))"
        return "UNKNOWN  # TODO: {}".format(field.__class__.__name__) 
Example 4
Project: django-translations   Author: bbmokhtari   File: models.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_translatable_fields(cls):
        """Return the model’s translatable fields."""
        if not hasattr(cls, '_cached_translatable_fields'):
            if cls.TranslatableMeta.fields is None:
                fields = []
                for field in cls._meta.get_fields():
                    if isinstance(
                                field,
                                (models.CharField, models.TextField,)
                            ) and not isinstance(
                                field,
                                models.EmailField
                            ) and not (
                                hasattr(field, 'choices') and field.choices
                            ):
                        fields.append(field)
            else:
                fields = [
                    cls._meta.get_field(field_name)
                    for field_name in cls.TranslatableMeta.fields
                ]
            cls._cached_translatable_fields = fields
        return cls._cached_translatable_fields 
Example 5
Project: SME-Livro-Aberto   Author: prefeiturasp   File: models.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def get_by_raw_indexer(self, indexer):
        # TODO: add test for the TextField
        info = indexer.split('.')

        try:
            empenho = self.get_queryset().get(
                an_empenho=int(info[0]),
                cd_orgao=info[1],
                cd_projeto_atividade=info[2],
                cd_categoria=int(info[3]),
                cd_grupo=int(info[4]),
                cd_modalidade=int(info[5]),
                cd_elemento=info[6],
                cd_fonte_de_recurso=info[7],
                cd_unidade=info[8],
                cd_subfuncao=info[9])
        except self.model.DoesNotExist:
            empenho = None

        return empenho 
Example 6
Project: media-webapp   Author: uisautomation   File: models.py    MIT License 6 votes vote down vote up
def ordered_media_item_queryset(self):
        """
        A queryset which returns the media items for the play list with the same ordering as
        :py:attr:`.media_items`.

        """
        all_media_items = (
            MediaItem.objects
            .filter(id__in=self.media_items)
            .annotate(index=expressions.Func(
                models.Value(self.media_items),
                functions.Cast(models.F('id'), output_field=models.TextField()),
                function='array_position'
            ))
            .order_by('index')
        )

        return all_media_items 
Example 7
Project: stream_framework_example   Author: wwj718   File: admin.py    MIT License 6 votes vote down vote up
def auto_configure_admin(model):
    '''
    Automatic configuration, let's make this smarter
    in the future
    '''
    from django.contrib import admin
    from django.db import models
    fields = model._meta.fields
    field_names = [f.name for f in fields]
    list_display = [f for f in field_names if f not in (
        'updated_at', 'created_at')]
    fields_in_list_display = list_display[:7]
    list_editable_fields = [
        f.name for f in fields if isinstance(f, models.IntegerField)]
    search_fields_list = [f.name for f in fields if isinstance(
        f, (models.TextField, models.CharField))]

    class StandardAdmin(admin.ModelAdmin):
        list_display = fields_in_list_display
        list_editable = list_editable_fields
        search_fields = search_fields_list
    return StandardAdmin 
Example 8
Project: news_proj   Author: TheoElia   File: search.py    MIT License 6 votes vote down vote up
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
        resolved = super().resolve_expression(query, allow_joins, reuse, summarize, for_save)
        resolved.set_source_expressions([
            Coalesce(
                expression
                if isinstance(expression.output_field, (CharField, TextField))
                else Cast(expression, TextField()),
                Value('')
            ) for expression in resolved.get_source_expressions()
        ])
        if self.config:
            if not hasattr(self.config, 'resolve_expression'):
                resolved.config = Value(self.config).resolve_expression(query, allow_joins, reuse, summarize, for_save)
            else:
                resolved.config = self.config.resolve_expression(query, allow_joins, reuse, summarize, for_save)
        return resolved 
Example 9
Project: tri.query   Author: TriOptima   File: db_compat.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setup_db_compat_django():
    from django.db.models import IntegerField, FloatField, TextField, BooleanField, AutoField, CharField, DateField, DateTimeField, DecimalField, EmailField, URLField, TimeField, ForeignKey, ManyToOneRel, ManyToManyField, ManyToManyRel

    # The order here is significant because of inheritance structure. More specific must be below less specific.
    register_variable_factory(CharField, Shortcut()),
    register_variable_factory(URLField, Shortcut(call_target__attribute='url')),
    register_variable_factory(TimeField, Shortcut(call_target__attribute='time')),
    register_variable_factory(EmailField, Shortcut(call_target__attribute='email')),
    register_variable_factory(DecimalField, Shortcut(call_target__attribute='decimal')),
    register_variable_factory(DateField, Shortcut(call_target__attribute='date')),
    register_variable_factory(DateTimeField, Shortcut(call_target__attribute='datetime')),
    register_variable_factory(BooleanField, Shortcut(call_target__attribute='boolean')),
    register_variable_factory(TextField, Shortcut(call_target__attribute='text')),
    register_variable_factory(FloatField, Shortcut(call_target__attribute='float')),
    register_variable_factory(IntegerField, Shortcut(call_target__attribute='integer')),

    register_variable_factory(AutoField, Shortcut(call_target__attribute='integer', show=False))
    register_variable_factory(ManyToManyField, Shortcut(call_target__attribute='many_to_many'))

    register_variable_factory(ManyToOneRel, None),
    register_variable_factory(ManyToManyRel, None),
    register_variable_factory(ForeignKey, Shortcut(call_target__attribute='foreign_key')) 
Example 10
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 11
Project: xadmin_bugfix   Author: vip68   File: filters.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (
            isinstance(field, models.CharField)
            and field.max_length > 20
            or isinstance(field, models.TextField)
        ) 
Example 12
Project: django-xadmin   Author: MarkHoo   File: filters.py    MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (
                isinstance(field, models.CharField)
                and field.max_length > 20
                or isinstance(field, models.TextField)
               ) 
Example 13
Project: django-xadmin   Author: MarkHoo   File: filters.py    MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (
                isinstance(field, models.CharField)
                and field.max_length > 20
                or isinstance(field, models.TextField)
               ) 
Example 14
Project: django-xadmin   Author: MarkHoo   File: filters.py    MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (
            isinstance(field, models.CharField)
            and field.max_length > 20
            or isinstance(field, models.TextField)
        ) 
Example 15
Project: simple-json-text-field   Author: irothschild   File: fields.py    MIT License 5 votes vote down vote up
def get_internal_type(self):
        return "TextField" 
Example 16
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 17
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_help_text_field(self):
        """
        The model should have a help_text field
        """
        field = OmniField._meta.get_field('help_text')
        self.assertIsInstance(field, models.TextField)
        self.assertTrue(field.blank)
        self.assertTrue(field.null) 
Example 18
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 = OmniCharField._meta.get_field('initial_data')
        self.assertIsInstance(field, models.TextField)
        self.assertTrue(field.blank)
        self.assertTrue(field.null) 
Example 19
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_choices_field(self):
        """
        The model should have a choices field
        """
        field = OmniChoiceField._meta.get_field('choices')
        self.assertIsInstance(field, models.TextField)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 20
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_choices_field(self):
        """
        The model should have a choices field
        """
        field = OmniMultipleChoiceField._meta.get_field('choices')
        self.assertIsInstance(field, models.TextField)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 21
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_template_field(self):
        """
        The model should define a template field
        """
        field = OmniFormEmailHandler._meta.get_field('template')
        self.assertIsInstance(field, models.TextField)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 22
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_template_field(self):
        """
        The model should have a template field
        """
        field = OmniFormEmailConfirmationHandler._meta.get_field('template')
        self.assertIsInstance(field, models.TextField)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 23
Project: tri.form   Author: TriOptima   File: test_forms.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_field_from_model_required():
    from django.db.models import TextField, Model

    class FooModel(Model):
        a = TextField(blank=True, null=True)
        b = TextField(blank=True, null=False)
        c = TextField(blank=False, null=True)
        d = TextField(blank=False, null=False)

    assert not Field.from_model(FooModel, 'a').required
    assert not Field.from_model(FooModel, 'b').required
    assert not Field.from_model(FooModel, 'c').required
    assert Field.from_model(FooModel, 'd').required 
Example 24
Project: tri.form   Author: TriOptima   File: test_forms.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_field_from_model_label():
    from django.db.models import TextField, Model

    class FooModel(Model):
        a = TextField(verbose_name='FOOO bar FOO')

    assert Field.from_model(FooModel, 'a').display_name == 'FOOO bar FOO' 
Example 25
Project: openhatch   Author: campbe13   File: 0006_rename_rel_to_project_exp.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'Link_ProjectExp_Tag'
        db.create_table('profile_link_projectexp_tag', (
            ('id', models.AutoField(primary_key=True)),
            ('tag', models.ForeignKey(orm.Tag)),
            ('project_exp', models.ForeignKey(orm.ProjectExp)),
            ('time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 9, 4, 847921))),
            ('source', models.CharField(max_length=200)),
        ))
        db.send_create_signal('profile', ['Link_ProjectExp_Tag'])
        
        # Adding model 'ProjectExp'
        db.create_table('profile_projectexp', (
            ('id', models.AutoField(primary_key=True)),
            ('person', models.ForeignKey(orm.Person)),
            ('project', models.ForeignKey(orm['search.Project'])),
            ('person_role', models.CharField(max_length=200)),
            ('tags', models.TextField()),
            ('time_record_was_created', models.DateTimeField()),
            ('url', models.URLField(max_length=200)),
            ('description', models.TextField()),
            ('time_start', models.DateTimeField()),
            ('time_finish', models.DateTimeField()),
            ('man_months', models.PositiveIntegerField()),
            ('primary_language', models.CharField(max_length=200)),
            ('source', models.CharField(max_length=100)),
        ))
        db.send_create_signal('profile', ['ProjectExp'])
        
        # Deleting model 'link_persontoprojectrelationship_tag'
        db.delete_table('profile_link_persontoprojectrelationship_tag')
        
        # Deleting model 'persontoprojectrelationship'
        db.delete_table('profile_persontoprojectrelationship')
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 9, 4, 301717))) 
Example 26
Project: openhatch   Author: campbe13   File: 0006_rename_rel_to_project_exp.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def backwards(self, orm):
        
        # Deleting model 'Link_ProjectExp_Tag'
        db.delete_table('profile_link_projectexp_tag')
        
        # Deleting model 'ProjectExp'
        db.delete_table('profile_projectexp')
        
        # Adding model 'link_persontoprojectrelationship_tag'
        db.create_table('profile_link_persontoprojectrelationship_tag', (
            ('person_to_project_relationship', models.ForeignKey(orm['profile.PersonToProjectRelationship'])),
            ('source', models.CharField(max_length=200)),
            ('tag', models.ForeignKey(orm['profile.Tag'])),
            ('time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 5, 1, 149232))),
            ('id', models.AutoField(primary_key=True)),
        ))
        db.send_create_signal('profile', ['link_persontoprojectrelationship_tag'])
        
        # Adding model 'persontoprojectrelationship'
        db.create_table('profile_persontoprojectrelationship', (
            ('description', models.TextField()),
            ('tags', models.TextField()),
            ('man_months', models.PositiveIntegerField()),
            ('primary_language', models.CharField(max_length=200)),
            ('id', models.AutoField(primary_key=True)),
            ('time_start', models.DateTimeField()),
            ('source', models.CharField(max_length=100)),
            ('url', models.URLField(max_length=200)),
            ('time_record_was_created', models.DateTimeField()),
            ('project', models.ForeignKey(orm['search.Project'])),
            ('person', models.ForeignKey(orm['profile.Person'])),
            ('time_finish', models.DateTimeField()),
            ('person_role', models.CharField(max_length=200)),
        ))
        db.send_create_signal('profile', ['persontoprojectrelationship'])
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 5, 1, 569217))) 
Example 27
Project: openhatch   Author: campbe13   File: 0001_initial.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'Person'
        db.create_table('profile_person', (
            ('id', models.AutoField(primary_key=True)),
            ('name', models.CharField(max_length=200)),
            ('username', models.CharField(max_length=200)),
            ('password_hash_md5', models.CharField(max_length=200)),
        ))
        db.send_create_signal('profile', ['Person'])
        
        # Adding model 'PersonToProjectRelationship'
        db.create_table('profile_persontoprojectrelationship', (
            ('id', models.AutoField(primary_key=True)),
            ('person', models.ForeignKey(orm.Person)),
            ('project', models.ForeignKey(orm['search.Project'])),
            ('person_role', models.CharField(max_length=200)),
            ('tags', models.TextField()),
            ('time_record_was_created', models.DateTimeField()),
            ('url', models.URLField(max_length=200)),
            ('description', models.TextField()),
            ('time_start', models.DateTimeField()),
            ('time_finish', models.DateTimeField()),
            ('man_months', models.PositiveIntegerField()),
            ('primary_language', models.CharField(max_length=200)),
            ('source', models.CharField(max_length=100)),
        ))
        db.send_create_signal('profile', ['PersonToProjectRelationship']) 
Example 28
Project: opadmin   Author: cc0411   File: adminx.py    GNU General Public License v3.0 5 votes vote down vote up
def get_field_style(self, attrs, db_field, style, **kwargs):
        if style == 'ueditor':
            if isinstance(db_field, UEditorField):
                return {'widget': XadminUEditorWidget(**db_field.formfield().widget.attrs)}
            if isinstance(db_field, TextField):
                return {'widget': XadminUEditorWidget}
        return attrs 
Example 29
Project: opadmin   Author: cc0411   File: filters.py    GNU General Public License v3.0 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (
                isinstance(field, models.CharField)
                and field.max_length > 20
                or isinstance(field, models.TextField)
               ) 
Example 30
Project: StormOnline   Author: stormsha   File: filters.py    Apache License 2.0 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (
                isinstance(field, models.CharField)
                and field.max_length > 20
                or isinstance(field, models.TextField)
               ) 
Example 31
Project: universal_notifications   Author: HealthByRo   File: fields.py    MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        warnings.warn("Django 1.9 features a native JsonField, this JSONField will "
                      "be removed somewhere after Django 1.8 becomes unsupported.",
                      DeprecationWarning)
        kwargs['default'] = kwargs.get('default', dict)
        models.TextField.__init__(self, *args, **kwargs) 
Example 32
Project: universal_notifications   Author: HealthByRo   File: fields.py    MIT License 5 votes vote down vote up
def get_prep_value(self, value):
        if not isinstance(value, six.string_types):
            return dumps(value)
        return super(models.TextField, self).get_prep_value(value) 
Example 33
Project: django-mptt-comments   Author: zmrenwu   File: models.py    MIT License 5 votes vote down vote up
def __init__(self, source, *args, **kwargs):
        self.source = source
        kwargs.setdefault('editable', False)
        super(TextField, self).__init__(*args, **kwargs) 
Example 34
Project: django-mptt-comments   Author: zmrenwu   File: models.py    MIT License 5 votes vote down vote up
def deconstruct(self):
        name, path, args, kwargs = super(TextField, self).deconstruct()
        args.append(self.source)

        return name, path, args, kwargs 
Example 35
Project: aas   Author: Uninett   File: mappings.py    GNU General Public License v3.0 5 votes vote down vote up
def prepare(self, field_name, model_for_field):
        field = model_for_field._meta.get_field(field_name)
        if isinstance(field, (models.CharField, models.TextField)) and not field.null:
            self.none_value = "" 
Example 36
Project: django-idcops   Author: Wenvki   File: list.py    Apache License 2.0 5 votes vote down vote up
def allow_search_fields(self, exclude=None, include=None):
        opts = self.opts

        def construct_search(model):
            exclude = [f.name for f in opts.fields if getattr(f, 'choices')]
            fields = model._meta.fields
            _fields = []
            for f in fields:
                if isinstance(f, models.CharField) and f.name not in exclude:
                    _fields.append(f.name + '__icontains')
            return _fields

        if not exclude:
            exclude = ['onidc', 'slug', 'created', 'modified']
        exclude.extend([f.name for f in opts.fields if getattr(f, 'choices')])

        fields = construct_search(self.model)
        for f in opts.fields:
            if exclude and f.name in exclude:
                continue
            if isinstance(f, models.ForeignKey):
                submodel = f.related_model
                for sub in submodel._meta.fields:
                    if exclude and sub.name in exclude:
                        continue
                    if isinstance(
                            sub, models.CharField) and not getattr(
                            sub, 'choices'):
                        fields.append(f.name + '__' + sub.name + '__icontains')
            if isinstance(f, (models.CharField, models.TextField)):
                fields.append(f.name + '__icontains')
        return fields 
Example 37
Project: django-idcops   Author: Wenvki   File: utils.py    Apache License 2.0 5 votes vote down vote up
def display_for_field(value, field, html=True, only_date=True):
    if getattr(field, 'flatchoices', None):
        if html and field.name == 'color' and value:
            return make_color_icon(value)
        return dict(field.flatchoices).get(value, '')
    elif html and (isinstance(field, (models.BooleanField, models.NullBooleanField))):
        return make_boolean_icon(value)
    elif isinstance(field, (models.BooleanField, models.NullBooleanField)):
        boolchoice = {False: "否", True: "是"}
        return boolchoice.get(value)
    elif value is None:
        return ""
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.ForeignKey) and value:
        rel_obj = field.related_model.objects.get(pk=value)
        if html and COLOR_FK_FIELD and isinstance(rel_obj, Option):
            text_color = rel_obj.color
            if not text_color:
                text_color = 'text-info'
            safe_value = format_html(
                '<span class="text-{}">{}</span>', text_color, rel_obj.text)
            return safe_value
        return force_text(rel_obj)
    elif isinstance(field, models.TextField) and value:
        return force_text(value)
    elif isinstance(field, models.DateTimeField):
        if only_date:
            return formats.date_format(value)
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value) 
Example 38
Project: django-conditioner   Author: omni-digital   File: test_misc.py    MIT License 5 votes vote down vote up
def test_model_message_field(self):
        """Test model 'message' field"""
        field = self.model._meta.get_field('message')

        self.assertIsInstance(field, models.TextField)
        self.assertEqual(field.verbose_name, 'message') 
Example 39
Project: ops22   Author: spark8103   File: filters.py    MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (isinstance(field, models.CharField) and field.max_length > 20) or isinstance(field, models.TextField) 
Example 40
Project: DeerU   Author: gojuukaze   File: fields.py    GNU General Public License v3.0 5 votes vote down vote up
def formfield(self, **kwargs):
        defaults = {'widget': ConfigWidget,
                    'max_length': self.max_length}
        defaults.update(kwargs)
        defaults['widget'] = ConfigWidget
        return super(TextField, self).formfield(**defaults) 
Example 41
Project: django-survey-formset   Author: hamdigdoura   File: models.py    MIT License 5 votes vote down vote up
def types_text(self):
        return self.filter(type='TextField') 
Example 42
Project: mudong_blog   Author: mudong1991   File: filters.py    GNU General Public License v2.0 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (isinstance(field, models.CharField) and field.max_length > 20) or isinstance(field, models.TextField) 
Example 43
Project: django-seo   Author: whyflyru   File: fields.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, head=True, editable=True, populate_from=NotSet, 
                 verbose_name=None, valid_tags=None, choices=None, field=models.TextField,
                 field_kwargs=None, help_text=None):
        if field_kwargs is None: 
            field_kwargs = {}
        field_kwargs.setdefault('default', "")
        field_kwargs.setdefault('blank', True)
        super(Raw, self).__init__(None, head, editable, populate_from, valid_tags, choices, help_text, verbose_name, field, field_kwargs) 
Example 44
Project: news   Author: kuc2477   File: django.py    MIT License 5 votes vote down vote up
def create_news_abc(schedule_model):
    """Abstract base news model factory.

    :param schedule_model: Schedule model to use as news's schedule.
    :type schedule_model: Any concrete schedule model of abc models from
        :func:`~create_abc_schedule` factory function.
    :returns: A abstract base news model.
    :rtype: Abstract base django model of
        :class:`~news.models.AbstractNews` implementation

    """
    class AbstractBaseNews(models.Model, AbstractNews):
        schedule = models.ForeignKey(
            schedule_model, related_name='news_list',
            db_index=True
        )

        parent = models.ForeignKey(
            'self', related_name='children',
            db_index=True, blank=True, null=True
        )

        url = models.URLField()
        author = models.CharField(max_length=AUTHOR_MAX_LENGTH, null=True)
        title = models.CharField(max_length=TITLE_MAX_LENGTH)
        summary = models.TextField()
        content = models.TextField()
        image = models.URLField(null=True)
        published = models.DateTimeField(blank=True, null=True)
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)

        class Meta:
            abstract = True
            unique_together = (('schedule', 'url'),)
    return AbstractBaseNews 
Example 45
Project: django-binder   Author: CodeYellowBV   File: views.py    MIT License 5 votes vote down vote up
def field_needs_nullability_check(self, field):
		if isinstance(field, (models.CharField, models.TextField, models.BooleanField)):
			if field.blank and not field.null:
				return True

		return False 
Example 46
Project: django-binder   Author: CodeYellowBV   File: orderable_agg.py    MIT License 5 votes vote down vote up
def output_field(self):
		return TextField(self.source_expressions[0].output_field) 
Example 47
Project: django-binder   Author: CodeYellowBV   File: views.py    MIT License 5 votes vote down vote up
def field_needs_nullability_check(self, field):
		if isinstance(field, (models.CharField, models.TextField, models.BooleanField)):
			if field.blank and not field.null:
				return True

		return False 
Example 48
Project: django-binder   Author: CodeYellowBV   File: orderable_agg.py    MIT License 5 votes vote down vote up
def output_field(self):
		return TextField(self.source_expressions[0].output_field) 
Example 49
Project: django-exmodel   Author: sorl   File: tests.py    ISC License 5 votes vote down vote up
def test_b(self):
        attrs = get_mixins_attrs(mixins_b)
        self.assertTrue(isinstance(attrs['a'], models.CharField))
        self.assertTrue(attrs.get('__str__'))
        self.assertTrue(isinstance(attrs['b'], models.TextField)) 
Example 50
Project: django-exmodel   Author: sorl   File: tests.py    ISC License 5 votes vote down vote up
def test_c(self):
        attrs = get_mixins_attrs(mixins_c)
        self.assertEqual(attrs['a'], 'a')
        self.assertTrue(attrs.get('__str__'))
        self.assertTrue(isinstance(attrs['b'], models.TextField))
        self.assertTrue(isinstance(attrs['c'], models.BooleanField)) 
Example 51
Project: palanaeum   Author: Palanaeum   File: models.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def update(self):
        lines = self.entry.lines.all()
        text_vector = pg_search.SearchVector(models.Value(strip_tags(self.entry.note), output_field=models.TextField()),
                                             weight='C', config='english')

        for tag in self.entry.tags.all():
            text_vector += pg_search.SearchVector(models.Value(tag.name, output_field=models.TextField()), weight='A',
                                                  config='english')

        for tag in self.entry.event.tags.all():
            text_vector += pg_search.SearchVector(models.Value(tag.name, output_field=models.TextField()), weight='C',
                                                  config='english')

        if lines.exists():
            speaker_vectors = []

            for line in lines:
                text_vector += pg_search.SearchVector(
                    models.Value(strip_tags(line.text), output_field=models.TextField()),
                    weight='B', config='english')
                speaker_vectors.append(pg_search.SearchVector(
                    models.Value(strip_tags(line.speaker), output_field=models.TextField()),
                    weight='A', config='english'))
                text_vector += pg_search.SearchVector(
                    models.Value(strip_tags(line.speaker), output_field=models.TextField()),
                    weight='D', config='english')

            speaker_vector = speaker_vectors[0]
            for sv in speaker_vectors[1:]:
                speaker_vector += sv

            self.speaker_vector = speaker_vector

        self.text_vector = text_vector
        self.save() 
Example 52
Project: weibo-analysis-system   Author: Superbsco   File: filters.py    MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (
            isinstance(field, models.CharField)
            and field.max_length > 20
            or isinstance(field, models.TextField)
        ) 
Example 53
Project: carnetdumaker   Author: TamiaLab   File: fields.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def get_internal_type(self):
        return "TextField" 
Example 54
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 55
Project: alchemist   Author: shitpaster   File: jsonschema.py    MIT License 5 votes vote down vote up
def convert_modelfield(self, name, field, json_schema):
        target_def = {
            'title': pretty_name(name),
            'description': getattr(field, 'help_text', None),
            'x-schema-form' : {}
        }
        
        if isinstance(field, models.CharField):
            target_def['type'] = 'string'
            target_def['maxlength'] = field.max_length
        elif isinstance(field, models.TextField):
            target_def['type'] = 'string'
            target_def['x-schema-form'] = {"type": "textarea"}
        if isinstance(field, models.DateField):
            target_def['type'] = 'string'
            target_def['format'] = 'date'
        elif isinstance(field, models.DateTimeField):
            target_def['type'] = 'string'
            target_def['format'] = 'datetime'
        elif isinstance(field, (models.DecimalField, models.FloatField)):
            target_def['type'] = 'number'
        elif isinstance(field, models.IntegerField):
            target_def['type'] = 'integer'
        elif isinstance(field, models.EmailField):
            target_def['type'] = 'string'
            target_def['format'] = 'email'
        elif isinstance(field, (models.NullBooleanField, models.BooleanField)):
            target_def['type'] = 'boolean'
        if isinstance(field, models.URLField):
            target_def['type'] = 'string'
            target_def['format'] = 'uri'
        else:
            target_def['type'] = 'string'


        if hasattr(field, 'choices') and field.choices:
            target_def['enum'] = [choice[0] for choice in field.choices]

        return target_def 
Example 56
Project: djangocms-comments   Author: Nekmo   File: admin.py    MIT License 5 votes vote down vote up
def get_queryset(self, request):
        qs = super(CommentAdmin, self).get_queryset(request)
        if django.VERSION >= (1, 8):
            # Concat is not available in 1.7 and 1.6
            qs = qs.annotate(author_sort=Concat('author_type', 'author_id', output_field=TextField()))
            qs = qs.annotate(page_sort=Concat('page_type', 'page_id', output_field=TextField()))
        return qs 
Example 57
Project: blogghar   Author: v1k45   File: fields.py    MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(SimpleMdeField, self).__init__(*args, **kwargs)
        # using SimpleMdeWidget for TextField
        self.widget = SimpleMdeWidget() 
Example 58
Project: AgendaTCC   Author: agendaTCC   File: models.py    GNU General Public License v2.0 5 votes vote down vote up
def __unicode__(self):
        return self.tipo
# class EmailAutomatico(models.Model):
#     class Meta:
#         verbose_name = 'E-mail Automatico'
#         verbose_name_plural = 'E-mails Automaticos'
#         unique_together = (("gerencia", "tipo"),)
#     gerencia = models.ForeignKey(GerenciarEmails)
#     tipo = models.CharField(max_length=1, verbose_name=u'Tipo', choices = TIPO_AUTOMATICO, null = True, blank= True)
#     periodo_antes = models.CharField(max_length = 255,null=True, blank=True)
#     periodo_depois = models.CharField(max_length = 255,null=True, blank=True)
#     data = models.DateField(auto_now=True, null=True, blank=True)
#     titulo = models.CharField(verbose_name=u'Título',max_length = 255,null = True, blank= True)
#     corpo = models.TextField(null = True, blank= True) 
Example 59
Project: myblog   Author: myminwang   File: filters.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (
            isinstance(field, models.CharField)
            and field.max_length > 20
            or isinstance(field, models.TextField)
        ) 
Example 60
Project: CTF_AWD_Platform   Author: xuchaoa   File: filters.py    MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (
            isinstance(field, models.CharField)
            and field.max_length > 20
            or isinstance(field, models.TextField)
        ) 
Example 61
Project: django_OA   Author: abaoMAO   File: filters.py    GNU General Public License v3.0 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (
            isinstance(field, models.CharField)
            and field.max_length > 20
            or isinstance(field, models.TextField)
        ) 
Example 62
Project: ok-seo   Author: LowerDeez   File: mixins.py    MIT License 5 votes vote down vote up
def is_text_field(field):
        return isinstance(field, models.TextField) 
Example 63
Project: docker-django-polymer-starter-kit   Author: JTarball   File: models.py    ISC License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.internal_type=kwargs.pop('internal_type', 'CharField') # or TextField
        super(StringListField, self).__init__(*args, **kwargs) 
Example 64
Project: morango   Author: learningequality   File: core.py    MIT License 5 votes vote down vote up
def char_ids_list(self):
        return (
            self.annotate(id_cast=Cast("id", TextField()))
            # remove dashes from char uuid
            .annotate(
                fixed_id=Func(F("id_cast"), Value("-"), Value(""), function="replace")
            )
            # return as list
            .values_list("fixed_id", flat=True)
        ) 
Example 65
Project: django-toolkit   Author: alexhayes   File: fields.py    MIT License 5 votes vote down vote up
def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_db_prep_value(value)

#class CommaSeparatedEmailField(TextField):
#    #__metaclass__ = SubfieldBase
#
#    def to_python(self, value):
#        print 'to_python', value
#        if not value:
#            return
#        if isinstance(value, list):
#            return value
#        return [address.strip() for address in value.split(',')]
#
#    def get_db_prep_value(self, value):
#        print 'get_db_prep_value', value
#        if not value:
#            return
#        return ','.join(unicode(s) for s in value)
#
#    def value_to_string(self, obj):
#        print 'value_to_string', obj
#        value = self._get_val_from_obj(obj)
#        return self.get_db_prep_value(value)
#
##    def formfield(self, **kwargs):
##        defaults = {'widget': MultiEmailField}
##        defaults.update(kwargs)
##        return super(CommaSeparatedEmailField, self).formfield(**defaults) 
Example 66
Project: django-leonardo   Author: django-leonardo   File: models.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 67
def backwards(self, orm):
        
        # Deleting field 'ProjectExp.time_start'
        db.delete_column('profile_projectexp', 'time_start')
        
        # Deleting field 'ProjectExp.last_touched'
        db.delete_column('profile_projectexp', 'last_touched')
        
        # Deleting field 'Tag.tag_type'
        db.delete_column('profile_tag', 'tag_type_id')
        
        # Deleting field 'ProjectExp.time_finish'
        db.delete_column('profile_projectexp', 'time_finish')
        
        # Adding field 'Tag.type'
        db.add_column('profile_tag', 'type', models.CharField(max_length=50))
        
        # Adding field 'ProjectExp.tags'
        db.add_column('profile_projectexp', 'tags', models.TextField())
        
        # Changing field 'Link_ProjectExp_Tag.time_record_was_created'
        db.alter_column('profile_link_projectexp_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 50, 22, 475279)))
        
        # Changing field 'Person.last_touched'
        db.alter_column('profile_person', 'last_touched', models.DateTimeField())
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 50, 22, 339421)))
        
        # Changing field 'ProjectExp.url'
        db.alter_column('profile_projectexp', 'url', models.URLField(max_length=200))
        
        # Changing field 'ProjectExp.man_months'
        db.alter_column('profile_projectexp', 'man_months', models.PositiveIntegerField())
        
        # Changing field 'ProjectExp.source'
        db.alter_column('profile_projectexp', 'source', models.CharField(max_length=100))
        
        # Changing field 'ProjectExp.primary_language'
        db.alter_column('profile_projectexp', 'primary_language', models.CharField(max_length=200))
        
        # Changing field 'ProjectExp.time_record_was_created'
        db.alter_column('profile_projectexp', 'time_record_was_created', models.DateTimeField()) 
Example 68
Project: chattR   Author: patrickstocklin   File: layermapping.py    GNU General Public License v2.0 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
                isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
            if model_field.max_length and len(val) > model_field.max_length:
                raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                    (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except DecimalInvalidOperation:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2]  # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal(
                    'A DecimalField with max_digits %d, decimal_places %d must '
                    'round to an absolute value less than 10^%d.' %
                    (model_field.max_digits, model_field.decimal_places, max_prec)
                )
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except ValueError:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val 
Example 69
Project: TESTGIT   Author: B-ROY   File: layermapping.py    Apache License 2.0 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
            isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
                if model_field.max_length and len(val) > model_field.max_length:
                    raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                        (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2] # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal('A DecimalField with max_digits %d, decimal_places %d must round to an absolute value less than 10^%d.' %
                                     (model_field.max_digits, model_field.decimal_places, max_prec))
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val 
Example 70
Project: AneMo   Author: jspargo   File: layermapping.py    GNU General Public License v2.0 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
                isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
                if model_field.max_length and len(val) > model_field.max_length:
                    raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                        (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except DecimalInvalidOperation:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2]  # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal('A DecimalField with max_digits %d, decimal_places %d must round to an absolute value less than 10^%d.' %
                                     (model_field.max_digits, model_field.decimal_places, max_prec))
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except ValueError:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val 
Example 71
Project: GTDWeb   Author: lanbing510   File: layermapping.py    GNU General Public License v2.0 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
                isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
            if model_field.max_length and len(val) > model_field.max_length:
                raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                    (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except DecimalInvalidOperation:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2]  # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal(
                    'A DecimalField with max_digits %d, decimal_places %d must '
                    'round to an absolute value less than 10^%d.' %
                    (model_field.max_digits, model_field.decimal_places, max_prec)
                )
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except ValueError:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val 
Example 72
Project: liberator   Author: libscie   File: layermapping.py    Creative Commons Zero v1.0 Universal 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
                isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
            if model_field.max_length and len(val) > model_field.max_length:
                raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                    (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except DecimalInvalidOperation:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2]  # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal(
                    'A DecimalField with max_digits %d, decimal_places %d must '
                    'round to an absolute value less than 10^%d.' %
                    (model_field.max_digits, model_field.decimal_places, max_prec)
                )
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except ValueError:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val 
Example 73
Project: Fun5G   Author: OpenWinCon   File: layermapping.py    Apache License 2.0 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
                isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
            if model_field.max_length and len(val) > model_field.max_length:
                raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                    (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except DecimalInvalidOperation:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2]  # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal(
                    'A DecimalField with max_digits %d, decimal_places %d must '
                    'round to an absolute value less than 10^%d.' %
                    (model_field.max_digits, model_field.decimal_places, max_prec)
                )
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except ValueError:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val 
Example 74
Project: Vigtech-Services   Author: VigTech   File: layermapping.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
                isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
            if model_field.max_length and len(val) > model_field.max_length:
                raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                    (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except DecimalInvalidOperation:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2]  # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal(
                    'A DecimalField with max_digits %d, decimal_places %d must '
                    'round to an absolute value less than 10^%d.' %
                    (model_field.max_digits, model_field.decimal_places, max_prec)
                )
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except ValueError:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val 
Example 75
Project: PopularityBased-SearchEngine   Author: rsunder10   File: layermapping.py    MIT License 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
                isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
            if model_field.max_length and len(val) > model_field.max_length:
                raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                    (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except DecimalInvalidOperation:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2]  # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal(
                    'A DecimalField with max_digits %d, decimal_places %d must '
                    'round to an absolute value less than 10^%d.' %
                    (model_field.max_digits, model_field.decimal_places, max_prec)
                )
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except ValueError:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val 
Example 76
Project: mudong_blog   Author: mudong1991   File: layermapping.py    GNU General Public License v2.0 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
                isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
            if model_field.max_length and len(val) > model_field.max_length:
                raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                    (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except DecimalInvalidOperation:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2]  # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal(
                    'A DecimalField with max_digits %d, decimal_places %d must '
                    'round to an absolute value less than 10^%d.' %
                    (model_field.max_digits, model_field.decimal_places, max_prec)
                )
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except ValueError:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val 
Example 77
Project: forum-xblock   Author: DANCEcollaborative   File: layermapping.py    MIT License 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
            isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = unicode(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
                if len(val) > model_field.max_length:
                    raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                        (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2] # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal('A DecimalField with max_digits %d, decimal_places %d must round to an absolute value less than 10^%d.' %
                                     (model_field.max_digits, model_field.decimal_places, max_prec))
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val 
Example 78
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 79
Project: Gypsy   Author: benticarlos   File: layermapping.py    MIT License 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
                isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
            if model_field.max_length and len(val) > model_field.max_length:
                raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                    (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except DecimalInvalidOperation:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2]  # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal(
                    'A DecimalField with max_digits %d, decimal_places %d must '
                    'round to an absolute value less than 10^%d.' %
                    (model_field.max_digits, model_field.decimal_places, max_prec)
                )
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except ValueError:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val 
Example 80
Project: tribune   Author: alex-muliande   File: layermapping.py    MIT License 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
                isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
            if model_field.max_length and len(val) > model_field.max_length:
                raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                    (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except DecimalInvalidOperation:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2]  # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal(
                    'A DecimalField with max_digits %d, decimal_places %d must '
                    'round to an absolute value less than 10^%d.' %
                    (model_field.max_digits, model_field.decimal_places, max_prec)
                )
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except ValueError:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val