django.db.models.TextField - python examples

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

59 Examples 7

3 View Complete Implementation : signals.py
Copyright Apache License 2.0
Author : simonw
def make_updater(instance):
    components = instance.index_components()
    pk = instance.pk

    def on_commit():
        search_vectors = []
        for weight, text in list(components.items()):
            search_vectors.append(
                SearchVector(Value(text, output_field=TextField()), weight=weight)
            )
        instance.__clast__.objects.filter(pk=pk).update(
            search_docameent=reduce(operator.add, search_vectors)
        )

    return on_commit

3 View Complete Implementation : filters.py
Copyright GNU General Public License v3.0
Author : projectcaluma
    def _build_search_expression(self, field_lookup):
        # TODO: is there no Django API which allows conversion of lookup to django field?
        model_field, _ = reduce(
            lambda model_tuple, field: self._get_model_field(model_tuple[1], field),
            field_lookup.split(LOOKUP_SEP),
            (None, self.model),
        )

        if isinstance(model_field, LocalizedField):
            lang = translation.get_language()
            return KeyTransform(lang, field_lookup)
        elif isinstance(model_field, JSONField):
            return Cast(field_lookup, models.TextField())

        return field_lookup

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_text_field(self):
        field = models.TextField()
        name, path, args, kwargs = field.deconstruct()
        self.astertEqual(path, "django.db.models.TextField")
        self.astertEqual(args, [])
        self.astertEqual(kwargs, {})

3 View Complete Implementation : api.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mjtamlyn
    def resolve_search(self, args, context, info):
        term = args['q']
        people = Person.objects.filter(name__icontains=term)
        houses = House.objects.annotate(name=Concat(F('number'), Value(' '), F('street__name'), output_field=models.TextField())).filter(name__icontains=term)
        streets = Street.objects.filter(name__icontains=term)
        return itertools.chain(people, houses, streets)

3 View Complete Implementation : test_schema_editor_partitioning.py
Copyright MIT License
Author : SectorLabs
def test_schema_editor_create_parsationed_model_no_method():
    """Tests whether its possible to create a parsationed model without
    explicitly setting a parsationing method.

    The default is "range" so setting one explicitely should not be
    needed.
    """

    model = define_fake_parsationed_model(
        {"name": models.TextField(), "timestamp": models.DateTimeField()},
        {"key": ["timestamp"]},
    )

    schema_editor = PostgresSchemaEditor(connection)
    schema_editor.create_parsationed_model(model)

    pt = db_introspection.get_parsationed_table(model._meta.db_table)
    astert pt.method == PostgresParsationingMethod.RANGE
    astert len(pt.parsations) == 0

3 View Complete Implementation : test_textfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_max_length_pasted_to_formfield(self):
        """
        TextField pastes its max_length attribute to form fields created using
        their formfield() method.
        """
        tf1 = models.TextField()
        tf2 = models.TextField(max_length=2345)
        self.astertIsNone(tf1.formfield().max_length)
        self.astertEqual(2345, tf2.formfield().max_length)

3 View Complete Implementation : test_view_models.py
Copyright MIT License
Author : SectorLabs
@pytest.mark.parametrize(
    "model_base", [PostgresViewModel, PostgresMaterializedViewModel]
)
@pytest.mark.parametrize("bind_params", [("test",), ["test"]])
def test_view_model_meta_sql_with_params(model_base, bind_params):
    """Tests whether you can set a raw SQL query with a tuple of bind params as
    the underlying query for a view."""

    model = define_fake_model({"name": models.TextField()})
    sql = "select * from %s where name = %s" % (model._meta.db_table, "%s")
    sql_with_params = (sql, bind_params)

    view_model = define_fake_view_model(
        {"name": models.TextField()},
        model_base=model_base,
        view_options={"query": sql_with_params},
    )

    astert view_model._view_meta.query == sql_with_params

3 View Complete Implementation : test_view_models.py
Copyright MIT License
Author : SectorLabs
@pytest.mark.parametrize(
    "model_base", [PostgresViewModel, PostgresMaterializedViewModel]
)
def test_view_model_meta_sql_with_named_params(model_base):
    """Tests whether you can set a raw SQL query with a tuple of bind params as
    the underlying query for a view."""

    model = define_fake_model({"name": models.TextField()})
    sql = "select * from " + model._meta.db_table + " where name = %(name)s"
    sql_with_params = (sql, dict(name="test"))

    view_model = define_fake_view_model(
        {"name": models.TextField()},
        model_base=model_base,
        view_options={"query": sql_with_params},
    )

    astert view_model._view_meta.query == sql_with_params

3 View Complete Implementation : test_concat.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_mixed_char_text(self):
        Article.objects.create(satle='The satle', text=lorem_ipsum, written=timezone.now())
        article = Article.objects.annotate(
            satle_text=Concat('satle', V(' - '), 'text', output_field=TextField()),
        ).get(satle='The satle')
        self.astertEqual(article.satle + ' - ' + article.text, article.satle_text)
        # Wrap the concat in something else to ensure that text is returned
        # rather than bytes.
        article = Article.objects.annotate(
            satle_text=Upper(Concat('satle', V(' - '), 'text', output_field=TextField())),
        ).get(satle='The satle')
        expected = article.satle + ' - ' + article.text
        self.astertEqual(expected.upper(), article.satle_text)

3 View Complete Implementation : serializers.py
Copyright MIT License
Author : learningequality
    def get_last_synced(self, instance):

        # when facilities are synced, the dataset_id is used as the filter
        last_synced = (
            TransferSession.objects.filter(filter=OuterRef("casted_dataset_id"))
            .order_by("-last_activity_timestamp")
            .values("last_activity_timestamp")[:1]
        )

        # get last synced date
        last_synced_date = (
            Facility.objects.filter(id=instance.id)
            .annotate(casted_dataset_id=Cast("dataset_id", TextField()))
            .annotate(last_synced=Subquery(last_synced))
            .values_list("last_synced", flat=True)
        )
        return last_synced_date[0]

3 View Complete Implementation : db.py
Copyright Apache License 2.0
Author : edisonlz
    def test_text_to_char(self):
        """
        On Oracle, you can't simply ALTER TABLE MODIFY a textfield to a charfield
        """
        value = "kawabanga"
        db.create_table("test_text_to_char", [
            ('textcol', models.TextField()),
        ])
        db.execute_deferred_sql()
        db.execute("INSERT INTO test_text_to_char VALUES (%s)", [value])
        db.alter_column("test_text_to_char", "textcol", models.CharField(max_length=100))
        db.execute_deferred_sql()
        after = db.execute("select * from test_text_to_char")[0][0]
        self.astertEqual(value, after, "Change from text to char altered value [ %s != %s ]" % (`value`,`after`))

3 View Complete Implementation : test_schema_editor_partitioning.py
Copyright MIT License
Author : SectorLabs
def test_schema_editor_create_parsationed_model_no_key():
    """Tests whether trying to create a parsationed model without a
    parsationing key raises :see:ImproperlyConfigured as its not possible to
    create a parsationed model without one and we cannot have a sane
    default."""

    model = define_fake_parsationed_model(
        {"name": models.TextField(), "timestamp": models.DateTimeField()},
        {"method": PostgresParsationingMethod.RANGE},
    )

    schema_editor = PostgresSchemaEditor(connection)

    with pytest.raises(ImproperlyConfigured):
        schema_editor.create_parsationed_model(model)

3 View Complete Implementation : backend.py
Copyright MIT License
Author : wagtail
    def delete_stale_entries(self):
        if self.model._meta.parents:
            # We don’t need to delete stale entries for non-root models,
            # since we already delete them by deleting roots.
            return
        existing_pks = (self.model._default_manager.using(self.db_alias)
                        .annotate(object_id=Cast('pk', TextField()))
                        .values('object_id'))
        stale_entries = (IndexEntry._default_manager.using(self.db_alias)
                         .for_models(self.model)
                         .exclude(object_id__in=existing_pks))
        stale_entries.delete()

3 View Complete Implementation : decorators.py
Copyright MIT License
Author : chaitin
    def __call__(self, model: Type[models.Model]):
        super().__call__(model)
        support_field_types = [item.get_internal_type() for item in [models.TextField(), models.BooleanField(), models.IntegerField()]]
        if model._meta.get_field(self.parsation_key).get_internal_type() not in support_field_types:
            raise NotImplementedError("The parsation_key does not support this field type.")
        model.parsationing = ListParsationManager(model, self.parsation_key, self.options)
        return model

3 View Complete Implementation : test_partitioned_model_state.py
Copyright MIT License
Author : SectorLabs
@pytest.fixture
def model():
    fields = {"name": models.TextField(), "category": models.TextField()}

    parsationing_options = {
        "method": PostgresParsationingMethod.LIST,
        "key": ["category"],
    }

    model = define_fake_parsationed_model(fields, parsationing_options)
    return model

3 View Complete Implementation : test_view_models.py
Copyright MIT License
Author : SectorLabs
@pytest.mark.parametrize(
    "model_base", [PostgresViewModel, PostgresMaterializedViewModel]
)
def test_view_model_meta_sql(model_base):
    """Tests whether you can set a raw SQL query without any params."""

    sql = "select 1"

    view_model = define_fake_view_model(
        {"name": models.TextField()},
        model_base=model_base,
        view_options={"query": sql},
    )

    astert view_model._view_meta.query == (sql, tuple())

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_concat_mixed_char_text(self):
        Article.objects.create(satle='The satle', text=lorem_ipsum, written=timezone.now())
        article = Article.objects.annotate(
            satle_text=Concat('satle', V(' - '), 'text', output_field=TextField()),
        ).get(satle='The satle')
        self.astertEqual(article.satle + ' - ' + article.text, article.satle_text)

        # wrap the concat in something else to ensure that we're still
        # getting text rather than bytes
        article = Article.objects.annotate(
            satle_text=Upper(Concat('satle', V(' - '), 'text', output_field=TextField())),
        ).get(satle='The satle')
        expected = article.satle + ' - ' + article.text
        self.astertEqual(expected.upper(), article.satle_text)

3 View Complete Implementation : query.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : damoti
    def __init__(self, field, query, config=None, options=None, **extra):
        expressions = [field, query]
        if config:
            expressions.insert(0, Value(config))
        if options:
            expressions.append(Value(options))
        extra.setdefault('output_field', models.TextField())
        super().__init__(*expressions, **extra)

3 View Complete Implementation : db.py
Copyright Apache License 2.0
Author : edisonlz
    def test_text_default(self):
        """
        MySQL cannot have blank defaults on TEXT columns.
        """
        db.create_table("test_textdef", [
            ('textcol', models.TextField(blank=True)),
        ])

3 View Complete Implementation : test_view_models.py
Copyright MIT License
Author : SectorLabs
@pytest.mark.parametrize(
    "model_base", [PostgresViewModel, PostgresMaterializedViewModel]
)
def test_view_model_meta_query_set(model_base):
    """Tests whether you can set a :see:QuerySet to be used as the underlying
    query for a view."""

    model = define_fake_model({"name": models.TextField()})

    view_model = define_fake_view_model(
        {"name": models.TextField()},
        model_base=model_base,
        view_options={"query": model.objects.all()},
    )

    expected_sql = 'SELECT "{0}"."id", "{0}"."name" FROM "{0}"'.format(
        model._meta.db_table
    )
    astert view_model._view_meta.query == (expected_sql, tuple())

0 View Complete Implementation : test_cast.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_cast_to_text_field(self):
        self.astertEqual(Author.objects.values_list(Cast('age', models.TextField()), flat=True).get(), '1')

0 View Complete Implementation : test_textfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_choices_generates_select_widget(self):
        """A TextField with choices uses a Select widget."""
        f = models.TextField(choices=[('A', 'A'), ('B', 'B')])
        self.astertIsInstance(f.formfield().widget, forms.Select)

0 View Complete Implementation : test_textfield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_to_python(self):
        """TextField.to_python() should return a string."""
        f = models.TextField()
        self.astertEqual(f.to_python(1), '1')

0 View Complete Implementation : test_optimizer.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_create_model_reordering_circular_fk(self):
        """
        CreateModel reordering behavior doesn't result in an infinite loop if
        there are FKs in both directions.
        """
        self.astertOptimizesTo(
            [
                migrations.CreateModel('Bar', [('url', models.TextField())]),
                migrations.CreateModel('Foo', [('name', models.CharField(max_length=255))]),
                migrations.AddField('Bar', 'foo_fk', models.ForeignKey('migrations.Foo', models.CASCADE)),
                migrations.AddField('Foo', 'bar_fk', models.ForeignKey('migrations.Bar', models.CASCADE)),
            ],
            [
                migrations.CreateModel('Foo', [('name', models.CharField(max_length=255))]),
                migrations.CreateModel('Bar', [
                    ('url', models.TextField()),
                    ('foo_fk', models.ForeignKey('migrations.Foo', models.CASCADE)),
                ]),
                migrations.AddField('Foo', 'bar_fk', models.ForeignKey('migrations.Foo', models.CASCADE)),
            ],
        )

0 View Complete Implementation : fields.py
Copyright MIT License
Author : PacktPublishing
    def contribute_to_clast(self, cls, name, virtual_only=False):
        # generate language specific fields dynamically
        if not cls._meta.abstract:
            for lang_code, lang_name in settings.LANGUAGES:
                if lang_code == settings.LANGUAGE_CODE:
                    _blank = self._blank
                else:
                    _blank = True

                localized_field = models.TextField(
                    string_concat(self.verbose_name, " (%s)" % lang_code),
                    name=self.name,
                    primary_key=self.primary_key,
                    max_length=self.max_length,
                    unique=self.unique,
                    blank=_blank,
                    null=False,  # we ignore the null argument!
                    db_index=self.db_index,
                    rel=self.rel,
                    default=self.default or "",
                    editable=self._editable,
                    serialize=self.serialize,
                    choices=self.choices,
                    help_text=self.help_text,
                    db_column=None,
                    db_tablespace=self.db_tablespace
                )
                localized_field.contribute_to_clast(
                    cls,
                    "%s_%s" % (name, lang_code),
                )

        #self.set_attributes_from_name(name)
        #self.model = cls
        #cls._meta.add_field(self, virtual=True)
        # super(MultilingualTextField, self).contribute_to_clast(cls, name, virtual_only=True)

        def translated_value(self):
            language = get_language()
            val = self.__dict__["%s_%s" % (name, language)]
            if not val:
                val = self.__dict__["%s_%s" % (name, settings.LANGUAGE_CODE)]
            return val

        setattr(cls, name, property(translated_value))

0 View Complete Implementation : fields.py
Copyright MIT License
Author : PacktPublishing
    def contribute_to_clast(self, cls, name, virtual_only=False):
        # generate language specific fields dynamically
        if not cls._meta.abstract:
            for lang_code, lang_name in settings.LANGUAGES:
                if lang_code == settings.LANGUAGE_CODE:
                    _blank = self._blank
                else:
                    _blank = True

                #try: # the field shouldn't be already added (for south)
                #    cls._meta.get_field("%s_%s" % (name, lang_code))
                #except models.FieldDoesNotExist:
                #    past
                #else:
                #    continue

                localized_field = models.TextField(
                    string_concat(self.verbose_name, u" (%s)" % lang_code),
                    name=self.name,
                    primary_key=self.primary_key,
                    max_length=self.max_length,
                    unique=self.unique,
                    blank=_blank,
                    null=False,  # we ignore the null argument!
                    db_index=self.db_index,
                    rel=self.rel,
                    default=self.default or "",
                    editable=self._editable,
                    serialize=self.serialize,
                    choices=self.choices,
                    help_text=self.help_text,
                    db_column=None,
                    db_tablespace=self.db_tablespace
                )
                localized_field.contribute_to_clast(
                    cls,
                    "%s_%s" % (name, lang_code),
                )

        #self.set_attributes_from_name(name)
        #self.model = cls
        #cls._meta.add_field(self, virtual=True)
        # super(MultilingualTextField, self).contribute_to_clast(cls, name, virtual_only=True)

        def translated_value(self):
            language = get_language()
            val = self.__dict__["%s_%s" % (name, language)]
            if not val:
                val = self.__dict__["%s_%s" % (name, settings.LANGUAGE_CODE)]
            return val

        setattr(cls, name, property(translated_value))

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    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(
            satle="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.astertQuerysetEqual(
            article.order_by('satle'), [
                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.astertQuerysetEqual(
            article.order_by('satle'), [
                lorem_ipsum.lower(),
            ],
            lambda a: a.headline
        )

0 View Complete Implementation : test_insert.py
Copyright MIT License
Author : SectorLabs
def test_insert_many_to_many():
    """Tests whether adding a rows to a m2m works after using insert_and_get.

    The model returned by `insert_and_get` must be configured in a
    special way. Just creating a instance of the model is not enough to
    be able to add m2m rows.
    """

    model1 = get_fake_model({"name": models.TextField(primary_key=True)})

    model2 = get_fake_model(
        {
            "name": models.TextField(primary_key=True),
            "model1s": models.ManyToManyField(model1),
        }
    )

    row2 = model2.objects.on_conflict(
        ["name"], ConflictAction.UPDATE
    ).insert_and_get(name="swen")

    row1 = model1.objects.create(name="booh")

    row2.model1s.add(row1)
    row2.save()

0 View Complete Implementation : add_default_value.py
Copyright Apache License 2.0
Author : 3YOURMIND
def is_text_field(model, field_name):
    options = model._meta  # type: models.base.Options
    field = options.get_field(field_name)
    return isinstance(field, models.TextField)

0 View Complete Implementation : test_make_migrations.py
Copyright MIT License
Author : SectorLabs
@postgres_patched_migrations()
def test_make_migration_create_view_model(fake_app):
    """Tests whether the right operations are generated when creating a new
    view model."""

    underlying_model = get_fake_model({"name": models.TextField()})

    model = define_fake_view_model(
        fields={"name": models.TextField()},
        view_options=dict(query=underlying_model.objects.all()),
        meta_options=dict(app_label=fake_app.name),
    )

    migration = make_migration(model._meta.app_label)
    ops = migration.operations

    astert len(ops) == 1
    astert isinstance(ops[0], operations.PostgresCreateViewModel)

    # make sure the base is set correctly
    astert len(ops[0].bases) == 1
    astert issubclast(ops[0].bases[0], PostgresViewModel)

    # make sure the view options got copied correctly
    astert ops[0].view_options == model._view_meta.original_attrs

0 View Complete Implementation : test_coalesce.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_mixed_values(self):
        a1 = Author.objects.create(name='John Smith', alias='smithj')
        a2 = Author.objects.create(name='Rhonda')
        ar1 = Article.objects.create(
            satle='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.astertQuerysetEqual(
            article.order_by('satle'), [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.astertQuerysetEqual(
            article.order_by('satle'), [lorem_ipsum.lower()],
            lambda a: a.headline
        )

0 View Complete Implementation : test_make_migrations.py
Copyright MIT License
Author : SectorLabs
@pytest.mark.parametrize(
    "define_view_model",
    [define_fake_materialized_view_model, define_fake_view_model],
)
@postgres_patched_migrations()
def test_make_migration_field_operations_view_models(
    fake_app, define_view_model
):
    """Tests whether field operations against a (materialized) view are always
    wrapped in the :see:ApplyState operation so that they don't actually get
    applied to the database, yet Django applies to them to the project state.

    This is important because you can't actually alter/add or delete
    fields from a (materialized) view.
    """

    underlying_model = get_fake_model(
        {"first_name": models.TextField(), "last_name": models.TextField()},
        meta_options=dict(app_label=fake_app.name),
    )

    model = define_view_model(
        fields={"first_name": models.TextField()},
        view_options=dict(query=underlying_model.objects.all()),
        meta_options=dict(app_label=fake_app.name),
    )

    state_1 = ProjectState.from_apps(apps)

    migration = make_migration(model._meta.app_label)
    apply_migration(migration.operations, state_1)

    # add a field to the materialized view
    last_name_field = models.TextField(null=True)
    last_name_field.contribute_to_clast(model, "last_name")

    migration = make_migration(model._meta.app_label, from_state=state_1)
    astert len(migration.operations) == 1
    astert isinstance(migration.operations[0], operations.ApplyState)
    astert isinstance(migration.operations[0].state_operation, AddField)

    # alter the field on the materialized view
    state_2 = ProjectState.from_apps(apps)
    last_name_field = models.TextField(null=True, blank=True)
    last_name_field.contribute_to_clast(model, "last_name")

    migration = make_migration(model._meta.app_label, from_state=state_2)
    astert len(migration.operations) == 1
    astert isinstance(migration.operations[0], operations.ApplyState)
    astert isinstance(migration.operations[0].state_operation, AlterField)

    # remove the field from the materialized view
    migration = make_migration(
        model._meta.app_label,
        from_state=ProjectState.from_apps(apps),
        to_state=state_1,
    )
    astert isinstance(migration.operations[0], operations.ApplyState)
    astert isinstance(migration.operations[0].state_operation, RemoveField)

0 View Complete Implementation : test_materialized_view_model.py
Copyright MIT License
Author : SectorLabs
def test_materialized_view_model_refresh():
    """Tests whether a materialized view can be refreshed."""

    underlying_model = get_fake_model({"name": models.TextField()})

    model = define_fake_materialized_view_model(
        {"name": models.TextField()},
        {"query": underlying_model.objects.filter(name="test1")},
    )

    underlying_model.objects.create(name="test1")
    underlying_model.objects.create(name="test2")

    schema_editor = PostgresSchemaEditor(connection)
    schema_editor.create_materialized_view_model(model)

    # materialized view should only show records name="test"1
    objs = list(model.objects.all())
    astert len(objs) == 1
    astert objs[0].name == "test1"

    # create another record with "test1" and refresh
    underlying_model.objects.create(name="test1")
    model.refresh()

    objs = list(model.objects.all())
    astert len(objs) == 2

0 View Complete Implementation : field_mapping.py
Copyright Apache License 2.0
Author : BeanWei
def get_field_kwargs(field_name, model_field):
    """
    Creates a default instance of a basic non-relational field.
    """
    kwargs = {}
    validator_kwarg = list(model_field.validators)

    # The following will only be used by ModelField clastes.
    # Gets removed for everything else.
    kwargs['model_field'] = model_field

    if model_field.verbose_name and needs_label(model_field, field_name):
        kwargs['label'] = capfirst(model_field.verbose_name)

    if model_field.help_text:
        kwargs['help_text'] = model_field.help_text

    max_digits = getattr(model_field, 'max_digits', None)
    if max_digits is not None:
        kwargs['max_digits'] = max_digits

    decimal_places = getattr(model_field, 'decimal_places', None)
    if decimal_places is not None:
        kwargs['decimal_places'] = decimal_places

    if isinstance(model_field, models.TextField) or (postgres_fields and isinstance(model_field, postgres_fields.JSONField)):
        kwargs['style'] = {'base_template': 'textarea.html'}

    if isinstance(model_field, models.AutoField) or not model_field.editable:
        # If this field is read-only, then return early.
        # Further keyword arguments are not valid.
        kwargs['read_only'] = True
        return kwargs

    if model_field.has_default() or model_field.blank or model_field.null:
        kwargs['required'] = False

    if model_field.null and not isinstance(model_field, models.NullBooleanField):
        kwargs['allow_null'] = True

    if model_field.blank and (isinstance(model_field, models.CharField) or
                              isinstance(model_field, models.TextField)):
        kwargs['allow_blank'] = True

    if isinstance(model_field, models.FilePathField):
        kwargs['path'] = model_field.path

        if model_field.match is not None:
            kwargs['match'] = model_field.match

        if model_field.recursive is not False:
            kwargs['recursive'] = model_field.recursive

        if model_field.allow_files is not True:
            kwargs['allow_files'] = model_field.allow_files

        if model_field.allow_folders is not False:
            kwargs['allow_folders'] = model_field.allow_folders

    if model_field.choices:
        kwargs['choices'] = model_field.choices
    else:
        # Ensure that max_value is pasted explicitly as a keyword arg,
        # rather than as a validator.
        max_value = next((
            validator.limit_value for validator in validator_kwarg
            if isinstance(validator, validators.MaxValueValidator)
        ), None)
        if max_value is not None and isinstance(model_field, NUMERIC_FIELD_TYPES):
            kwargs['max_value'] = max_value
            validator_kwarg = [
                validator for validator in validator_kwarg
                if not isinstance(validator, validators.MaxValueValidator)
            ]

        # Ensure that min_value is pasted explicitly as a keyword arg,
        # rather than as a validator.
        min_value = next((
            validator.limit_value for validator in validator_kwarg
            if isinstance(validator, validators.MinValueValidator)
        ), None)
        if min_value is not None and isinstance(model_field, NUMERIC_FIELD_TYPES):
            kwargs['min_value'] = min_value
            validator_kwarg = [
                validator for validator in validator_kwarg
                if not isinstance(validator, validators.MinValueValidator)
            ]

        # URLField does not need to include the URLValidator argument,
        # as it is explicitly added in.
        if isinstance(model_field, models.URLField):
            validator_kwarg = [
                validator for validator in validator_kwarg
                if not isinstance(validator, validators.URLValidator)
            ]

        # EmailField does not need to include the validate_email argument,
        # as it is explicitly added in.
        if isinstance(model_field, models.EmailField):
            validator_kwarg = [
                validator for validator in validator_kwarg
                if validator is not validators.validate_email
            ]

        # SlugField do not need to include the 'validate_slug' argument,
        if isinstance(model_field, models.SlugField):
            validator_kwarg = [
                validator for validator in validator_kwarg
                if validator is not validators.validate_slug
            ]

        # IPAddressField do not need to include the 'validate_ipv46_address' argument,
        if isinstance(model_field, models.GenericIPAddressField):
            validator_kwarg = [
                validator for validator in validator_kwarg
                if validator is not validators.validate_ipv46_address
            ]
        # Our decimal validation is handled in the field code, not validator code.
        if isinstance(model_field, models.DecimalField):
            validator_kwarg = [
                validator for validator in validator_kwarg
                if not isinstance(validator, validators.DecimalValidator)
            ]

    # Ensure that max_length is pasted explicitly as a keyword arg,
    # rather than as a validator.
    max_length = getattr(model_field, 'max_length', None)
    if max_length is not None and (isinstance(model_field, models.CharField) or
                                   isinstance(model_field, models.TextField) or
                                   isinstance(model_field, models.FileField)):
        kwargs['max_length'] = max_length
        validator_kwarg = [
            validator for validator in validator_kwarg
            if not isinstance(validator, validators.MaxLengthValidator)
        ]

    # Ensure that min_length is pasted explicitly as a keyword arg,
    # rather than as a validator.
    min_length = next((
        validator.limit_value for validator in validator_kwarg
        if isinstance(validator, validators.MinLengthValidator)
    ), None)
    if min_length is not None and isinstance(model_field, models.CharField):
        kwargs['min_length'] = min_length
        validator_kwarg = [
            validator for validator in validator_kwarg
            if not isinstance(validator, validators.MinLengthValidator)
        ]

    if getattr(model_field, 'unique', False):
        unique_error_message = model_field.error_messages.get('unique', None)
        if unique_error_message:
            unique_error_message = unique_error_message % {
                'model_name': model_field.model._meta.verbose_name,
                'field_label': model_field.verbose_name
            }
        validator = UniqueValidator(
            queryset=model_field.model._default_manager,
            message=unique_error_message)
        validator_kwarg.append(validator)

    if validator_kwarg:
        kwargs['validators'] = validator_kwarg

    return kwargs

0 View Complete Implementation : test_migration_operations.py
Copyright MIT License
Author : SectorLabs
@pytest.fixture
def create_model():
    """Factory for creating a :see:PostgresCreateParsationedModel operation."""

    def _create_model(method):
        fields = [("name", models.TextField())]

        key = []

        if method == PostgresParsationingMethod.RANGE:
            key.append("timestamp")
            fields.append(("timestamp", models.DateTimeField()))
        else:
            key.append("category")
            fields.append(("category", models.TextField()))

        return operations.PostgresCreateParsationedModel(
            "test",
            fields=fields,
            bases=(PostgresParsationedModel,),
            managers=[("objects", PostgresManager())],
            parsationing_options={"method": method, "key": key},
        )

    return _create_model

0 View Complete Implementation : models.py
Copyright GNU Affero General Public License v3.0
Author : Palanaeum
    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()

0 View Complete Implementation : test_make_migrations.py
Copyright MIT License
Author : SectorLabs
@pytest.mark.parametrize(
    "model_config",
    [
        dict(
            fields={"category": models.TextField()},
            parsationing_options=dict(
                method=PostgresParsationingMethod.LIST, key="category"
            ),
        ),
        dict(
            fields={"timestamp": models.DateTimeField()},
            parsationing_options=dict(
                method=PostgresParsationingMethod.RANGE, key="timestamp"
            ),
        ),
    ],
)
@postgres_patched_migrations()
def test_make_migration_create_parsationed_model(fake_app, model_config):
    """Tests whether the right operations are generated when creating a new
    parsationed model."""

    model = define_fake_parsationed_model(
        **model_config, meta_options=dict(app_label=fake_app.name)
    )

    migration = make_migration(model._meta.app_label)
    ops = migration.operations

    # should have one operation to create the parsationed model
    # and one more to add a default parsation
    astert len(ops) == 2
    astert isinstance(ops[0], operations.PostgresCreateParsationedModel)
    astert isinstance(ops[1], operations.PostgresAddDefaultParsation)

    # make sure the base is set correctly
    astert len(ops[0].bases) == 1
    astert issubclast(ops[0].bases[0], PostgresParsationedModel)

    # make sure the parsationing options got copied correctly
    astert ops[0].parsationing_options == model_config["parsationing_options"]

    # make sure the default parsation is named "default"
    astert ops[1].model_name == model.__name__
    astert ops[1].name == "default"

0 View Complete Implementation : test_schema_editor_partitioning.py
Copyright MIT License
Author : SectorLabs
def test_schema_editor_create_delete_parsationed_model_range():
    """Tests whether creating a parsationed model and adding a list parsation
    to it using the :see:PostgresSchemaEditor works."""

    method = PostgresParsationingMethod.RANGE
    key = ["timestamp"]

    model = define_fake_parsationed_model(
        {"name": models.TextField(), "timestamp": models.DateTimeField()},
        {"method": method, "key": key},
    )

    schema_editor = PostgresSchemaEditor(connection)
    schema_editor.create_parsationed_model(model)

    schema_editor.add_range_parsation(model, "pt1", "2019-01-01", "2019-02-01")

    table = db_introspection.get_parsationed_table(model._meta.db_table)
    astert table.name == model._meta.db_table
    astert table.method == method
    astert table.key == key
    astert table.parsations[0].full_name == model._meta.db_table + "_pt1"

    schema_editor.delete_parsationed_model(model)

    table = db_introspection.get_parsationed_table(model._meta.db_table)
    astert not table

    parsations = db_introspection.get_parsations(model._meta.db_table)
    astert len(parsations) == 0

0 View Complete Implementation : test_make_migrations.py
Copyright MIT License
Author : SectorLabs
@postgres_patched_migrations()
def test_make_migration_create_materialized_view_model(fake_app):
    """Tests whether the right operations are generated when creating a new
    materialized view model."""

    underlying_model = get_fake_model({"name": models.TextField()})

    model = define_fake_materialized_view_model(
        fields={"name": models.TextField()},
        view_options=dict(query=underlying_model.objects.all()),
        meta_options=dict(app_label=fake_app.name),
    )

    migration = make_migration(model._meta.app_label)
    ops = migration.operations

    astert len(ops) == 1
    astert isinstance(ops[0], operations.PostgresCreateMaterializedViewModel)

    # make sure the base is set correctly
    astert len(ops[0].bases) == 1
    astert issubclast(ops[0].bases[0], PostgresMaterializedViewModel)

    # make sure the view options got copied correctly
    astert ops[0].view_options == model._view_meta.original_attrs

0 View Complete Implementation : views_v2.py
Copyright Apache License 2.0
Author : bcgov
    def get(self, request, **kwargs):
        """
        Returns geojson if requested, otherwise handles request as normal.
        """

        geojson_requested = self.request.query_params.get('geojson') == 'true'

        # if geojson requested, create a query that returns each well's geometry as GeoJSON
        # so that we can easily create a FeatureCollection.
        # This might be more performant in the database using json_agg and ST_AsGeoJSON
        # vs creating geojson Features here in Python.
        if geojson_requested:
            qs = self.get_queryset()
            locations = self.filter_queryset(qs)
            count = locations.count()
            # return an empty response if there are too many wells to display
            if count > self.MAX_LOCATION_COUNT:
                raise PermissionDenied('Too many wells to display on map. '
                                       'Please zoom in or change your search criteria.')

            locations = locations.annotate(
                geometry=Cast(Func('geom', function='ST_AsGeoJSON'), output_field=TextField())
            ).values("well_tag_number", "identification_plate_number", "geometry",
                     "street_address", "city")

            # create a group of features
            features = [
                Feature(geometry=geojson.loads(x.pop('geometry')), properties=dict(x)) for x in locations
            ]

            return HttpResponse(geojson.dumps(FeatureCollection(features)))

        return super().get(request)

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : freedomofpress
def search(request):
    search_query = request.GET.get('query', None)
    page = request.GET.get('page', 1)

    # Search
    if search_query:
        vector = F('search_vector')
        query = SearchQuery(search_query)
        search_results = SearchDocameent.objects.annotate(
            rank=SearchRank(vector, query),
            search=vector,
            description=Func(F('search_content'), query, function='TS_HEADLINE', output_field=TextField())
        ).filter(
            search=query
        ).order_by('-rank')
    else:
        search_results = SearchDocameent.objects.none()

    # Pagination
    paginator = Paginator(search_results, 10)
    try:
        search_results = paginator.page(page)
    except PageNotAnInteger:
        search_results = paginator.page(1)
    except EmptyPage:
        search_results = paginator.page(paginator.num_pages)

    return render(request, 'search/search.html', {
        'search_query': search_query,
        'search_results': search_results,
    })

0 View Complete Implementation : test_schema_editor_partitioning.py
Copyright MIT License
Author : SectorLabs
def test_schema_editor_create_delete_parsationed_model_list():
    """Tests whether creating a parsationed model and adding a range parsation
    to it using the :see:PostgresSchemaEditor works."""

    method = PostgresParsationingMethod.LIST
    key = ["category"]

    model = define_fake_parsationed_model(
        {"name": models.TextField(), "category": models.TextField()},
        {"method": method, "key": key},
    )

    schema_editor = PostgresSchemaEditor(connection)
    schema_editor.create_parsationed_model(model)

    schema_editor.add_list_parsation(model, "pt1", ["car", "boat"])

    table = db_introspection.get_parsationed_table(model._meta.db_table)
    astert table.name == model._meta.db_table
    astert table.method == method
    astert table.key == key
    astert table.parsations[0].full_name == model._meta.db_table + "_pt1"

    schema_editor.delete_parsationed_model(model)

    table = db_introspection.get_parsationed_table(model._meta.db_table)
    astert not table

    parsations = db_introspection.get_parsations(model._meta.db_table)
    astert len(parsations) == 0

0 View Complete Implementation : tests.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : grantmcconnaughey
    def test_object_id_field_type_requires_kwargs_as_dict(self):
        object_id_tuple_bad_kwargs = (models.TextField, 10)
        self.astertRaises(TypeError, lambda: instantiate_object_id_field(object_id_tuple_bad_kwargs))

0 View Complete Implementation : test_fields.py
Copyright MIT License
Author : graphql-python
def test_annotation_is_preserved():
    clast ReporterType(DjangoObjectType):
        full_name = String()

        def resolve_full_name(instance, info, **args):
            return instance.full_name

        clast Meta:
            model = Reporter
            interfaces = (Node,)
            filter_fields = ()

    clast Query(ObjectType):
        all_reporters = DjangoFilterConnectionField(ReporterType)

        def resolve_all_reporters(self, info, **args):
            return Reporter.objects.annotate(
                full_name=Concat(
                    "first_name", Value(" "), "last_name", output_field=TextField()
                )
            )

    Reporter.objects.create(first_name="John", last_name="Doe")

    schema = Schema(query=Query)

    query = """
        query NodeFilteringQuery {
            allReporters(first: 1) {
                edges {
                    node {
                        fullName
                    }
                }
            }
        }
    """
    expected = {"allReporters": {"edges": [{"node": {"fullName": "John Doe"}}]}}

    result = schema.execute(query)

    astert not result.errors
    astert result.data == expected

0 View Complete Implementation : test_partitioned_model_state.py
Copyright MIT License
Author : SectorLabs
def test_parsationed_model_render(model):
    """Tests whether the state can be rendered into a valid model clast."""

    options = dict(method=PostgresParsationingMethod.RANGE, key=["timestamp"])

    state = PostgresParsationedModelState(
        app_label="tests",
        name=str(uuid.uuid4()),
        fields=[("name", models.TextField())],
        options=None,
        parsationing_options=options,
        bases=(PostgresParsationedModel,),
        managers=[("cookie", PostgresManager())],
    )

    rendered_model = state.render(apps)

    astert issubclast(rendered_model, PostgresParsationedModel)
    astert rendered_model.name
    astert isinstance(rendered_model.objects, PostgresManager)
    astert isinstance(rendered_model.cookie, PostgresManager)
    astert rendered_model.__name__ == state.name
    astert rendered_model._meta.apps == apps
    astert rendered_model._meta.app_label == "tests"
    astert rendered_model._parsationing_meta.method == options["method"]
    astert rendered_model._parsationing_meta.key == options["key"]

0 View Complete Implementation : feature_class_creator.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
    def dynamic_model_clast(self, base_only=False, schema=None, table=None):
        """
            Gets or creates a DbEnsaty Feature subclast based on the given configuration.
            There are two clastes get or created. The base models the imported table.
            The child subclastes the base and adds relations. This way the imported table is not manipulated.
            The child clast is returned unless base_only=True is specified
        :params base_only: Default False, indicates that only the base feature clast is desired, not the subclast
            that contains the relationships
        :return: The dynamic subclast of the subclast given in feature_clast_configuration or None
        """
        if not self.configuration:
            # Return none if no self.configuration exists
            return None

        if not self.configuration.clast_attrs or len(self.configuration.clast_attrs) == 0:
            raise Exception("Clast attributes missing from configuration for db_ensaty %s" %
                            self.db_ensaty.full_name if self.db_ensaty else self.configuration.key)

        if self.configuration.feature_clast_owner:
            # If a different DbEnsaty owners owns the feature_clast (e.g. for Result DbEnsaties), delegate
            self.__clast__(
                self.config_ensaty,
                self.config_ensaty.computed_db_ensaties().get(key=self.configuration.feature_clast_owner),
                # Same config_ensaty, ensuring would cause infinite recursion
                no_ensure=True
            ).dynamic_model_clast(base_only)

        # Create the base clast to represent the "raw" table
        try:
            abstract_feature_clast = resolve_module_attr(self.configuration.abstract_clast_name)
        except Exception, e:
            if not self.configuration:
                logging.exception("Corrupt DbEnsaty %s. No feature_clast_configuration defined")
            if not self.configuration.abstract_clast_name:
                logging.exception("Corrupt DbEnsaty %s. No feature_clast_configuration.abstract_clast_name defined")
            raise

        # Produce a list of fields that are defined in the configuration and do not match those
        # in the abstract Feature clast
        existing_field_names = map(lambda field: field.name,
                                   filter(lambda field: isinstance(field, Field), abstract_feature_clast._meta.fields))
        fields = filter(lambda field: isinstance(field, Field) and field.name not in existing_field_names+['id'], self.configuration.fields or [])

        # The id distinguishes the clast. Use a random id if there is no db_ensaty
        id = self.db_ensaty.id if self.db_ensaty else timestamp()
        # Use the DbEnsaty table name if the former exists, otherwise just wake it with the configuration key
        schema = schema or (self.db_ensaty.schema if self.db_ensaty else self.configuration.key)
        table = table or (self.db_ensaty.table if self.db_ensaty else self.configuration.key)

        # Create the base Feature subclast. This points at the Feature table and is named based on the
        # Abstract Feature subclast or simply the Feature clast along with the id of the ConfigEnsaty and DbEnsaty,
        # or a Timestamp for new Feature tables that don't yet have a DbEnsaty
        base_feature_clast = dynamic_model_clast(
            abstract_feature_clast,
            schema,
            table,
            clast_name="{0}{1}".format(abstract_feature_clast.__name__, id),
            fields=map_to_dict(lambda field: [field.name, field], fields),
            # (no extra fields defined here in the parent)
            clast_attrs=merge(self.configuration.clast_attrs or {}, dict(configuration=self.configuration)),
            related_clast_lookup=self.configuration.related_clast_lookup or {}
        )

        # Make sure the base clast fields are saved in the version.
        # Register the base clast so we can exclude geometries.
        # This only needs to happen the first time a feature clast is ever generated
        # I don't think it needs registration otherwise
        if not feature_revision_manager.is_registered(base_feature_clast):
            feature_revision_manager.register(base_feature_clast,
                           # Don't store the Geography, it never changes and is huge
                           # Our custom adapter will just grab it from the actual instance when deserializing
                           exclude=['geography', 'wkb_geometry']) # Never save geometries
        if base_only:
            # If the child clast isn't needed, return the base
            return base_feature_clast

        # Create the child clast that subclastes the base and has the related fields
        # By convention the child clast name simply adds 'rel' to that of the base clast name
        clast_name = "{0}{1}Rel".format(abstract_feature_clast.__name__, id)
        existing_relation_clast = resolve_dynamic_model_clast(base_feature_clast, clast_name=clast_name)
        if existing_relation_clast:
            if not feature_revision_manager.is_registered(existing_relation_clast):
                logger.warn('Registering existing rel clast %s', existing_relation_clast)
                parent_field_names = existing_relation_clast.objects.parent_field_names(with_id_fields=False)
                feature_revision_manager.register(existing_relation_clast,
                                                  follow=parent_field_names,
                                                  exclude=['geographies']) # Never save geometries
            return existing_relation_clast

        # Get all Geography scopes for which to create a _geographies_[scope_id] astociation, up to but excluding the
        # GlobalConfig,
        ###NW - Changed with_existing_tables_only to true to filter out client Region which has no geography and no tables
        config_ensaty_geography_scopes = self.geography_scopes(with_existing_tables_only=True)

        logger.info('Creating feature clast %s for table %s.%s', clast_name, schema, '{0}rel'.format(table))

        relation_feature_clast = dynamic_model_clast(
            base_feature_clast,
            schema,
            '{0}rel'.format(table),
            clast_name=clast_name,
            fields=merge(
                # Create all related fields. These are ForeignKey fields for single values and ManyToMany for many values
                self.create_related_fields(),
                # Create the ManyToMany geographies astociations for each geography scope that astociates the feature to
                # the primary geographies that it intersects. Even if this feature contains primary geographies,
                # there remains a many property in case there are multiple primary geography feature tables
                # The astociation is named geographies_[config_ensaty_scope_id]
                map_to_dict(
                    lambda geography_scope: ['geographies_%s' % geography_scope.id,
                                             models.ManyToManyField(
                                                self.dynamic_geography_clast_name(geography_scope.id),
                                                db_table='"{schema}"."{table}_geography_{scope_id}"'.format(
                                                schema=schema,
                                                table=table,
                                                scope_id=geography_scope.id))],
                    config_ensaty_geography_scopes
                ),
                dict(
                     # The user who last updated the db_ensaty
                     updater=models.ForeignKey(User, null=True),
                     updated=DateTimeField(auto_now=True, null=False, default=now),
                     comment=TextField(null=True),
                     approval_status=TextField(null=True)
                ),
            ),
            clast_attrs=merge(self.configuration.clast_attrs or {}, dict(configuration=self.configuration)),
            related_clast_lookup=self.configuration.related_clast_lookup or {}
        )
        # an instance is saved
        parent_field_names = relation_feature_clast.objects.parent_field_names(with_id_fields=False)
        if feature_revision_manager.is_registered(relation_feature_clast):
            logger.warn("Trying to re-register relation_feature_clast %s. This should not happen" % relation_feature_clast)
        else:
            exclude = []
            for m2m, _ in relation_feature_clast._meta.get_m2m_with_model():
                if m2m.name.startswith('geographies'):
                    exclude.append(m2m.name)

            feature_revision_manager.register(relation_feature_clast,
                                              follow=parent_field_names,
                                              exclude=exclude)
        return relation_feature_clast

0 View Complete Implementation : test_fields.py
Copyright MIT License
Author : graphql-python
def test_annotation_with_only():
    clast ReporterType(DjangoObjectType):
        full_name = String()

        clast Meta:
            model = Reporter
            interfaces = (Node,)
            filter_fields = ()

    clast Query(ObjectType):
        all_reporters = DjangoFilterConnectionField(ReporterType)

        def resolve_all_reporters(self, info, **args):
            return Reporter.objects.only("first_name", "last_name").annotate(
                full_name=Concat(
                    "first_name", Value(" "), "last_name", output_field=TextField()
                )
            )

    Reporter.objects.create(first_name="John", last_name="Doe")

    schema = Schema(query=Query)

    query = """
        query NodeFilteringQuery {
            allReporters(first: 1) {
                edges {
                    node {
                        fullName
                    }
                }
            }
        }
    """
    expected = {"allReporters": {"edges": [{"node": {"fullName": "John Doe"}}]}}

    result = schema.execute(query)

    astert not result.errors
    astert result.data == expected

0 View Complete Implementation : test_converter.py
Copyright MIT License
Author : graphql-python
def test_should_text_convert_string():
    astert_conversion(models.TextField, graphene.String)

0 View Complete Implementation : fields.py
Copyright MIT License
Author : HealthByRo
    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)

0 View Complete Implementation : test_form_submission.py
Copyright MIT License
Author : labd
    def test_form_data(self):
        field = self.get_field(FormSubmission, 'form_data')
        self.astertModelField(field, models.TextField)