Python django.db.models.TextField() Examples

The following are 30 code examples of django.db.models.TextField(). 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 also want to check out all available functions/classes of the module django.db.models , or try the search function .
Example #1
Source File: test_models_py.py    From django-collaborative with 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 #2
Source File: test_process_with_django.py    From eventsourcing with BSD 3-Clause "New" or "Revised" License 6 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
Source File: api.py    From chain-api with 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 #4
Source File: test_state.py    From djongo with 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 #5
Source File: test_ordinary_fields.py    From djongo with 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 #6
Source File: backend.py    From wagtail with 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 #7
Source File: archiver.py    From Archery with 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 #8
Source File: api.py    From chain-api with 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 #9
Source File: functions.py    From django-mysql with 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 #10
Source File: models.py    From django-field-history with 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 #11
Source File: test_state.py    From django-sqlserver with 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 #12
Source File: json.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
            warnings.warn(
                '"jsoneditor" module not available, to enable json mode '
                'please run: "pip install djongo[json]"', stacklevel=2)
            models.TextField.__init__(self, *args, **kwargs) 
Example #13
Source File: models.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def update_search(self):
        vectors = SearchVector(Value("", output_field=models.TextField()), config=settings.SEARCH_CONFIG)
        for weight in ["a", "b", "c", "d"]:
            if hasattr(self, "index_search_{}".format(weight)):
                content = getattr(self, "index_search_{}".format(weight))()
                vectors = vectors + SearchVector(Value(content, output_field=models.TextField()),
                                                 config=settings.SEARCH_CONFIG, weight=weight.upper())

        self.search_tsv = vectors 
Example #14
Source File: 0001_initial.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def combine_index(field_a, field_b):
    vector = SearchVector(Value(field_a, output_field=models.TextField()), config=settings.SEARCH_CONFIG, weight="A") + \
             SearchVector(Value(field_b, output_field=models.TextField()), config=settings.SEARCH_CONFIG, weight="B")

    return vector 
Example #15
Source File: test_autodetector.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_add_blank_textfield_and_charfield(self, mocked_ask_method):
        """
        #23405 - Adding a NOT NULL and blank `CharField` or `TextField`
        without default should not prompt for a default.
        """
        changes = self.get_changes([self.author_empty], [self.author_with_biography_blank])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, 'testapp', 1)
        self.assertOperationTypes(changes, 'testapp', 0, ["AddField", "AddField"])
        self.assertOperationAttributes(changes, 'testapp', 0, 0) 
Example #16
Source File: test_operations.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_add_binaryfield(self):
        """
        Tests the AddField operation on TextField/BinaryField.
        """
        project_state = self.set_up_test_model("test_adbinfl")

        Pony = project_state.apps.get_model("test_adbinfl", "Pony")
        pony = Pony.objects.create(weight=42)

        new_state = self.apply_operations("test_adbinfl", project_state, [
            migrations.AddField(
                "Pony",
                "blob",
                models.BinaryField(default=b"some text"),
            ),
            migrations.AddField(
                "Pony",
                "empty",
                models.BinaryField(default=b""),
            ),
            # If not properly quoted digits would be interpreted as an int.
            migrations.AddField(
                "Pony",
                "digits",
                models.BinaryField(default=b"42"),
            ),
            # Manual quoting is fragile and could trip on quotes. Refs #xyz.
            migrations.AddField(
                "Pony",
                "quotes",
                models.BinaryField(default=b'"\'"'),
            ),
        ])

        Pony = new_state.apps.get_model("test_adbinfl", "Pony")
        pony = Pony.objects.get(pk=pony.pk)
        # SQLite returns buffer/memoryview, cast to bytes for checking.
        self.assertEqual(bytes(pony.blob), b"some text")
        self.assertEqual(bytes(pony.empty), b"")
        self.assertEqual(bytes(pony.digits), b"42")
        self.assertEqual(bytes(pony.quotes), b'"\'"') 
Example #17
Source File: test_operations.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_add_textfield(self):
        """
        Tests the AddField operation on TextField.
        """
        project_state = self.set_up_test_model("test_adtxtfl")

        Pony = project_state.apps.get_model("test_adtxtfl", "Pony")
        pony = Pony.objects.create(weight=42)

        new_state = self.apply_operations("test_adtxtfl", project_state, [
            migrations.AddField(
                "Pony",
                "text",
                models.TextField(default="some text"),
            ),
            migrations.AddField(
                "Pony",
                "empty",
                models.TextField(default=""),
            ),
            # If not properly quoted digits would be interpreted as an int.
            migrations.AddField(
                "Pony",
                "digits",
                models.TextField(default="42"),
            ),
            # Manual quoting is fragile and could trip on quotes. Refs #xyz.
            migrations.AddField(
                "Pony",
                "quotes",
                models.TextField(default='"\'"'),
            ),
        ])

        Pony = new_state.apps.get_model("test_adtxtfl", "Pony")
        pony = Pony.objects.get(pk=pony.pk)
        self.assertEqual(pony.text, "some text")
        self.assertEqual(pony.empty, "")
        self.assertEqual(pony.digits, "42")
        self.assertEqual(pony.quotes, '"\'"') 
Example #18
Source File: test_operations.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_add_charfield(self):
        """
        Tests the AddField operation on TextField.
        """
        project_state = self.set_up_test_model("test_adchfl")

        Pony = project_state.apps.get_model("test_adchfl", "Pony")
        pony = Pony.objects.create(weight=42)

        new_state = self.apply_operations("test_adchfl", project_state, [
            migrations.AddField(
                "Pony",
                "text",
                models.CharField(max_length=10, default="some text"),
            ),
            migrations.AddField(
                "Pony",
                "empty",
                models.CharField(max_length=10, default=""),
            ),
            # If not properly quoted digits would be interpreted as an int.
            migrations.AddField(
                "Pony",
                "digits",
                models.CharField(max_length=10, default="42"),
            ),
            # Manual quoting is fragile and could trip on quotes. Refs #xyz.
            migrations.AddField(
                "Pony",
                "quotes",
                models.CharField(max_length=10, default='"\'"'),
            ),
        ])

        Pony = new_state.apps.get_model("test_adchfl", "Pony")
        pony = Pony.objects.get(pk=pony.pk)
        self.assertEqual(pony.text, "some text")
        self.assertEqual(pony.empty, "")
        self.assertEqual(pony.digits, "42")
        self.assertEqual(pony.quotes, '"\'"') 
Example #19
Source File: test_models.py    From django-user-management with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_name(self):
        expected = u'Cú Chulainn'
        model = self.model(name=expected)

        self.assertEqual(model.get_full_name(), expected)
        self.assertEqual(str(model), expected)
        field = get_field_by_name(self.model, 'name')[0]
        self.assertIsInstance(field, TextField) 
Example #20
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_add_non_blank_textfield_and_charfield(self, mocked_ask_method):
        """
        #23405 - Adding a NOT NULL and non-blank `CharField` or `TextField`
        without default should prompt for a default.
        """
        changes = self.get_changes([self.author_empty], [self.author_with_biography_non_blank])
        self.assertEqual(mocked_ask_method.call_count, 2)
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, 'testapp', 1)
        self.assertOperationTypes(changes, 'testapp', 0, ["AddField", "AddField"])
        self.assertOperationAttributes(changes, 'testapp', 0, 0) 
Example #21
Source File: test_operations.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_create_model_with_duplicate_field_name(self):
        with self.assertRaisesMessage(ValueError, 'Found duplicate value pink in CreateModel fields argument.'):
            migrations.CreateModel(
                "Pony",
                [
                    ("id", models.AutoField(primary_key=True)),
                    ("pink", models.TextField()),
                    ("pink", models.IntegerField(default=1)),
                ],
            ) 
Example #22
Source File: test_state.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_create_swappable(self):
        """
        Tests making a ProjectState from an Apps with a swappable model
        """
        new_apps = Apps(['migrations'])

        class Author(models.Model):
            name = models.CharField(max_length=255)
            bio = models.TextField()
            age = models.IntegerField(blank=True, null=True)

            class Meta:
                app_label = 'migrations'
                apps = new_apps
                swappable = 'TEST_SWAPPABLE_MODEL'

        author_state = ModelState.from_model(Author)
        self.assertEqual(author_state.app_label, 'migrations')
        self.assertEqual(author_state.name, 'Author')
        self.assertEqual([x for x, y in author_state.fields], ['id', 'name', 'bio', 'age'])
        self.assertEqual(author_state.fields[1][1].max_length, 255)
        self.assertIs(author_state.fields[2][1].null, False)
        self.assertIs(author_state.fields[3][1].null, True)
        self.assertEqual(author_state.options, {'swappable': 'TEST_SWAPPABLE_MODEL', 'indexes': []})
        self.assertEqual(author_state.bases, (models.Model, ))
        self.assertEqual(author_state.managers, []) 
Example #23
Source File: test_state.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_ignore_order_wrt(self):
        """
        Makes sure ProjectState doesn't include OrderWrt fields when
        making from existing models.
        """
        new_apps = Apps()

        class Author(models.Model):
            name = models.TextField()

            class Meta:
                app_label = "migrations"
                apps = new_apps

        class Book(models.Model):
            author = models.ForeignKey(Author, models.CASCADE)

            class Meta:
                app_label = "migrations"
                apps = new_apps
                order_with_respect_to = "author"

        # Make a valid ProjectState and render it
        project_state = ProjectState()
        project_state.add_model(ModelState.from_model(Author))
        project_state.add_model(ModelState.from_model(Book))
        self.assertEqual(
            [name for name, field in project_state.models["migrations", "book"].fields],
            ["id", "author"],
        ) 
Example #24
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_text_field(self):
        field = models.TextField()
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(path, "django.db.models.TextField")
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {}) 
Example #25
Source File: test_optimizer.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_create_model_add_field_not_through_fk(self):
        """
        AddField should NOT optimize into CreateModel if it's an FK to a model
        that's between them.
        """
        self.assertDoesNotOptimize(
            [
                migrations.CreateModel("Foo", [("name", models.CharField(max_length=255))]),
                migrations.CreateModel("Link", [("url", models.TextField())]),
                migrations.AddField("Foo", "link", models.ForeignKey("migrations.Link", models.CASCADE)),
            ],
        ) 
Example #26
Source File: tests.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_text_field(self):
        field = models.TextField()
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(path, "django.db.models.TextField")
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {}) 
Example #27
Source File: fields.py    From django-seo2 with MIT 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 #28
Source File: test_bug_migrations_in_base_models.py    From django-pgschemas with MIT License 5 votes vote down vote up
def patched_get_tenant_model(*args, **kwargs):
    class TenantModel(TenantMixin):
        dummy = models.TextField()

        class Meta:
            app_label = get_tenant_model()._meta.app_label

    return TenantModel 
Example #29
Source File: test_textfield.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_max_length_passed_to_formfield(self):
        """
        TextField passes its max_length attribute to form fields created using
        their formfield() method.
        """
        tf1 = models.TextField()
        tf2 = models.TextField(max_length=2345)
        self.assertIsNone(tf1.formfield().max_length)
        self.assertEqual(2345, tf2.formfield().max_length) 
Example #30
Source File: tests.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_coalesce_mixed_values(self):
        a1 = Author.objects.create(name='John Smith', alias='smithj')
        a2 = Author.objects.create(name='Rhonda')
        ar1 = Article.objects.create(
            title="How to Django",
            text=lorem_ipsum,
            written=timezone.now(),
        )
        ar1.authors.add(a1)
        ar1.authors.add(a2)

        # mixed Text and Char
        article = Article.objects.annotate(
            headline=Coalesce('summary', 'text', output_field=TextField()),
        )

        self.assertQuerysetEqual(
            article.order_by('title'), [
                lorem_ipsum,
            ],
            lambda a: a.headline
        )

        # mixed Text and Char wrapped
        article = Article.objects.annotate(
            headline=Coalesce(Lower('summary'), Lower('text'), output_field=TextField()),
        )

        self.assertQuerysetEqual(
            article.order_by('title'), [
                lorem_ipsum.lower(),
            ],
            lambda a: a.headline
        )