Python django.db.models.TextField() Examples

The following are 30 code examples for showing how to use django.db.models.TextField(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.db.models , or try the search function .

Example 1
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 2
Project: wagtail   Author: wagtail   File: backend.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def as_vector(self, texts, for_autocomplete=False):
        """
        Converts an array of strings into a SearchVector that can be indexed.
        """
        texts = [(text.strip(), weight) for text, weight in texts]
        texts = [(text, weight) for text, weight in texts if text]

        if not texts:
            return EMPTY_VECTOR

        search_config = self.autocomplete_config if for_autocomplete else self.config

        return ADD([
            SearchVector(Value(text, output_field=TextField()), weight=weight, config=search_config)
            for text, weight in texts
        ]) 
Example 3
Project: django-mysql   Author: adamchainz   File: functions.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, *expressions, **kwargs):
        separator = kwargs.pop("separator", ",")
        if len(kwargs) > 0:
            raise ValueError(
                "Invalid keyword arguments for ConcatWS: {}".format(
                    ",".join(kwargs.keys())
                )
            )

        if len(expressions) < 2:
            raise ValueError("ConcatWS must take at least two expressions")

        if not hasattr(separator, "resolve_expression"):
            separator = Value(separator)

        # N.B. if separator is "," we could potentially use list field
        output_field = TextField()
        super().__init__(separator, *expressions, output_field=output_field) 
Example 4
Project: django-field-history   Author: grantmcconnaughey   File: models.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def instantiate_object_id_field(object_id_class_or_tuple=models.TextField):
    """
    Instantiates and returns a model field for FieldHistory.object_id.

    object_id_class_or_tuple may be either a Django model field class or a
    tuple of (model_field, kwargs), where kwargs is a dict passed to
    model_field's constructor.
    """
    if isinstance(object_id_class_or_tuple, (list, tuple)):
        object_id_class, object_id_kwargs = object_id_class_or_tuple
    else:
        object_id_class = object_id_class_or_tuple
        object_id_kwargs = {}

    if not issubclass(object_id_class, models.fields.Field):
        raise TypeError('settings.%s must be a Django model field or (field, kwargs) tuple' % OBJECT_ID_TYPE_SETTING)
    if not isinstance(object_id_kwargs, dict):
        raise TypeError('settings.%s kwargs must be a dict' % OBJECT_ID_TYPE_SETTING)

    return object_id_class(db_index=True, **object_id_kwargs) 
Example 5
Project: django-collaborative   Author: propublica   File: test_models_py.py    License: MIT License 6 votes vote down vote up
def setUp(self):
        self.models_py = """
        from django.db import models

        class Tmp4Wlpvd0C(models.Model):
            timestamp = models.TextField(db_column='Timestamp', blank=True, null=True)
            question_with_short_answer_field = models.TextField(db_column='Question with short answer?')
            question_with_long_answer_field = models.TextField(db_column='Question with long answer?')
            checkbox_field = models.TextField(db_column='Checkbox?')
            option_with_dropdown_field = models.TextField(db_column='Option with dropdown?')
            multiple_choice_field = models.TextField(db_column='Multiple choice?')
            field_numeric_linear_scale_field = models.TextField(db_column=' Numeric linear scale?')
            multiple_choice_grid_row1_field = models.TextField(db_column='Multiple choice grid? [row1]')
            multiple_choice_grid_row2_field = models.TextField(db_column='Multiple choice grid? [row2]')
            checkbox_grid_row1_field = models.TextField(db_column='Checkbox grid? [row1]')
            checkbox_grid_row2_field = models.TextField(db_column='Checkbox grid? [row2]')
            what_date_field = models.DateField(db_column='What date?')
            what_time_field = models.TextField(db_column='What time?')
            """ 
Example 6
Project: django-sqlserver   Author: denisenkom   File: test_state.py    License: MIT License 6 votes vote down vote up
def test_custom_default_manager_added_to_the_model_state(self):
        """
        When the default manager of the model is a custom manager,
        it needs to be added to the model state.
        """
        new_apps = Apps(['migrations'])
        custom_manager = models.Manager()

        class Author(models.Model):
            objects = models.TextField()
            authors = custom_manager

            class Meta:
                app_label = 'migrations'
                apps = new_apps

        project_state = ProjectState.from_apps(new_apps)
        author_state = project_state.models['migrations', 'author']
        self.assertEqual(author_state.managers, [('authors', custom_manager)]) 
Example 7
Project: chain-api   Author: ResEnv   File: api.py    License: MIT License 6 votes vote down vote up
def schema_type_from_model_field(field):
    field_class = field.__class__
    if field_class == models.FloatField:
        return 'number', None
    elif field_class in [models.CharField, models.TextField]:
        return 'string', None
    elif field_class == models.DateTimeField:
        return 'string', 'date-time'
    elif field_class == models.BooleanField:
        return 'boolean', None
    elif field_class == models.ForeignKey:
        return 'string', 'url'
    else:
        raise NotImplementedError('Field type %s not recognized' % field_class)


# TODO: this should get the URL dynamically 
Example 8
Project: chain-api   Author: ResEnv   File: api.py    License: MIT License 6 votes vote down vote up
def sanitize_field_value(cls, field_name, value):
        '''Converts the given value to the correct python tyhttp://localhost:8080/people/1pe, for instance if
        the field is supposed to be a float field and the string "23" is given,
        it will be converted to 23.0

        NOTE - this currently only works for vanilla model fields, which serves
        our purposes for now'''
        field = cls.model._meta.get_field_by_name(field_name)[0]
        field_class = field.__class__
        if field_class == models.ForeignKey:
            lookup = lookup_associated_model_object(value)
            if lookup is None:
                raise BadRequestException(
                    "The url to the given resource does not exist.")
            return lookup
        # TextField missing to_python in Django 1.6
        elif field_class == models.TextField:
            if isinstance(value, six.string_types) or value is None:
                return value
            return smart_text(value)
        return field.to_python(value) 
Example 9
Project: Archery   Author: hhyo   File: archiver.py    License: Apache License 2.0 6 votes vote down vote up
def archive_log(request):
    """获取归档日志列表"""
    limit = int(request.GET.get('limit', 0))
    offset = int(request.GET.get('offset', 0))
    limit = offset + limit
    archive_id = request.GET.get('archive_id')

    archive_logs = ArchiveLog.objects.filter(archive=archive_id).annotate(
        info=Concat('cmd', V('\n'), 'statistics', output_field=TextField()))
    count = archive_logs.count()
    lists = archive_logs.order_by('-id')[offset:limit].values(
        'cmd', 'info', 'condition', 'mode', 'no_delete', 'select_cnt',
        'insert_cnt', 'delete_cnt', 'success', 'error_info', 'start_time', 'end_time'
    )
    # QuerySet 序列化
    rows = [row for row in lists]
    result = {"total": count, "rows": rows}
    # 返回查询结果
    return HttpResponse(json.dumps(result, cls=ExtendJSONEncoder, bigint_as_string=True),
                        content_type='application/json') 
Example 10
Project: djongo   Author: nesdis   File: test_ordinary_fields.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_max_length_warning(self):
        class Model(models.Model):
            value = models.TextField(db_index=True)
        field = Model._meta.get_field('value')
        field_type = field.db_type(connection)
        self.assertEqual(field.check(), [
            DjangoWarning(
                '%s does not support a database index on %s columns.'
                % (connection.display_name, field_type),
                hint=(
                    "An index won't be created. Silence this warning if you "
                    "don't care about it."
                ),
                obj=field,
                id='fields.W162',
            )
        ]) 
Example 11
Project: djongo   Author: nesdis   File: test_state.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_custom_default_manager_added_to_the_model_state(self):
        """
        When the default manager of the model is a custom manager,
        it needs to be added to the model state.
        """
        new_apps = Apps(['migrations'])
        custom_manager = models.Manager()

        class Author(models.Model):
            objects = models.TextField()
            authors = custom_manager

            class Meta:
                app_label = 'migrations'
                apps = new_apps

        project_state = ProjectState.from_apps(new_apps)
        author_state = project_state.models['migrations', 'author']
        self.assertEqual(author_state.managers, [('authors', custom_manager)]) 
Example 12
Project: StormOnline   Author: stormsha   File: filters.py    License: 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 13
Project: django-mptt-comments   Author: zmrenwu   File: models.py    License: 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 14
Project: django-mptt-comments   Author: zmrenwu   File: models.py    License: 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 15
Project: django-idcops   Author: Wenvki   File: list.py    License: 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 16
Project: django-idcops   Author: Wenvki   File: utils.py    License: 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 17
Project: yata   Author: Kivou-2000607   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def getPersonalstats(self, req=None):
        from player.personalstats_dic import d as personalstats_dic
        if req is None:
            return dict({})

        personnalstats = dict({})

        for k, v in req.items():
            s = personalstats_dic.get(k, {"category": "Unkown", "sub": "default", "type": "integer", "name": k})
            if s["category"] not in personnalstats:
                personnalstats[s["category"]] = [[], dict({})]
            if s["sub"] == "default":
                personnalstats[s["category"]][0].append([s["name"], v, s["type"]])
            else:
                if s["sub"] not in personnalstats[s["category"]][1]:
                    personnalstats[s["category"]][1][s["sub"]] = []
                personnalstats[s["category"]][1][s["sub"]].append([s["name"], v, s["type"]])

            if s["category"] == "Unkown":
                print(k, v)

        return personnalstats

# class News(models.Model):
#     player = models.ManyToManyField(Player, blank=True)
#     type = models.CharField(default="Info", max_length=16)
#     text = models.TextField()
#     authorId = models.IntegerField(default=2000607)  # hopefully it will be relevent not to put this as default some day...
#     authorName = models.CharField(default="Kivou", max_length=32)
#     date = models.DateTimeField(default=timezone.now)
#
#     def __str__(self):
#         return "{} of {:%Y/%M/%d} by {}".format(self.type, self.date, self.authorName)
#
#     def read(self):
#         return len(self.player.all()) 
Example 18
Project: DeerU   Author: gojuukaze   File: fields.py    License: 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 19
Project: django-seo   Author: whyflyru   File: fields.py    License: 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 20
Project: palanaeum   Author: Palanaeum   File: models.py    License: 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 21
Project: weibo-analysis-system   Author: Superbsco   File: filters.py    License: 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 22
Project: myblog   Author: myminwang   File: filters.py    License: 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 23
Project: CTF_AWD_Platform   Author: xuchaoa   File: filters.py    License: 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 24
Project: django_OA   Author: abaoMAO   File: filters.py    License: 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 25
Project: ishare   Author: jeeyshe   File: adminx.py    License: MIT License 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 26
Project: wagtail   Author: wagtail   File: backend.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def delete_stale_model_entries(self, model):
        existing_pks = (
            model._default_manager.using(self.db_alias)
            .annotate(object_id=Cast('pk', TextField()))
            .values('object_id')
        )
        content_types_pks = get_descendants_content_types_pks(model)
        stale_entries = (
            self.entries.filter(content_type_id__in=content_types_pks)
            .exclude(object_id__in=existing_pks)
        )
        stale_entries.delete() 
Example 27
Project: wagtail   Author: wagtail   File: fields.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_internal_type(self):
        return 'TextField' 
Example 28
Project: wagtail   Author: wagtail   File: replace_text.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def replace_in_model(model, from_text, to_text):
    text_field_names = [field.name for field in model._meta.fields if (
        isinstance(field, models.TextField)
        or isinstance(field, models.CharField)
    )
    ]
    updated_fields = []
    for field in text_field_names:
        field_value = getattr(model, field)
        if field_value and (from_text in field_value):
            updated_fields.append(field)
            setattr(model, field, field_value.replace(from_text, to_text))

    if updated_fields:
        model.save(update_fields=updated_fields) 
Example 29
Project: django-leonardo   Author: django-leonardo   File: models.py    License: 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 30
Project: tri.table   Author: TriOptima   File: db_compat.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup_db_compat_django():
    from tri_table import register_column_factory
    try:
        # noinspection PyUnresolvedReferences
        from django.db.models import IntegerField, FloatField, TextField, BooleanField, AutoField, CharField, DateField, DateTimeField, DecimalField, EmailField, TimeField, ForeignKey, ManyToOneRel, ManyToManyField, ManyToManyRel, UUIDField
    except ImportError:
        pass
    else:
        # The order here is significant because of inheritance structure. More specific must be below less specific.

        register_column_factory(CharField, Shortcut(call_target__attribute='text'))
        register_column_factory(UUIDField, Shortcut(call_target__attribute='text'))
        register_column_factory(TimeField, Shortcut(call_target__attribute='time'))
        register_column_factory(EmailField, Shortcut(call_target__attribute='email'))
        register_column_factory(DecimalField, Shortcut(call_target__attribute='decimal'))
        register_column_factory(DateField, Shortcut(call_target__attribute='date'))
        register_column_factory(DateTimeField, Shortcut(call_target__attribute='datetime'))
        register_column_factory(BooleanField, Shortcut(call_target__attribute='boolean'))
        register_column_factory(TextField, Shortcut(call_target__attribute='text'))
        register_column_factory(FloatField, Shortcut(call_target__attribute='float'))
        register_column_factory(IntegerField, Shortcut(call_target__attribute='integer'))
        register_column_factory(AutoField, Shortcut(call_target__attribute='integer', show=False))
        register_column_factory(ManyToOneRel, None)
        register_column_factory(ManyToManyField, Shortcut(call_target__attribute='many_to_many'))
        register_column_factory(ManyToManyRel, None)

        register_column_factory(ForeignKey, Shortcut(call_target__attribute='foreign_key'))