Python django.db.models.CharField() Examples

The following are 30 code examples for showing how to use django.db.models.CharField(). 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 want to check out the right sidebar which shows the related API usage.

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

Example 1
Project: timed-backend   Author: adfinis-sygroup   File: views.py    License: GNU Affero General Public License v3.0 7 votes vote down vote up
def get_queryset(self):
        date = self._extract_date()
        user = self.request.user
        queryset = get_user_model().objects.values("id")
        queryset = queryset.annotate(date=Value(date, DateField()))
        # last_reported_date filter is set, a date can only be calucated
        # for users with either at least one absence or report
        if date is None:
            users_with_reports = Report.objects.values("user").distinct()
            users_with_absences = Absence.objects.values("user").distinct()
            active_users = users_with_reports.union(users_with_absences)
            queryset = queryset.filter(id__in=active_users)

        queryset = queryset.annotate(
            pk=Concat("id", Value("_"), "date", output_field=CharField())
        )

        if not user.is_superuser:
            queryset = queryset.filter(Q(id=user.id) | Q(supervisors=user))

        return queryset 
Example 2
Project: timed-backend   Author: adfinis-sygroup   File: views.py    License: GNU Affero General Public License v3.0 7 votes vote down vote up
def get_queryset(self):
        date = self._extract_date()
        user = self._extract_user()

        queryset = models.AbsenceType.objects.values("id")
        queryset = queryset.annotate(date=Value(date, DateField()))
        queryset = queryset.annotate(user=Value(user.id, IntegerField()))
        queryset = queryset.annotate(
            pk=Concat(
                "user", Value("_"), "id", Value("_"), "date", output_field=CharField()
            )
        )

        # only myself, superuser and supervisors may see by absence balances
        current_user = self.request.user

        if not current_user.is_superuser:
            if current_user.id != user.id:
                if not current_user.supervisees.filter(id=user.id).exists():
                    return models.AbsenceType.objects.none()

        return queryset 
Example 3
Project: django-idcops   Author: Wenvki   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def allow_search_fields(cls, exclude=None):
    opts = cls._meta
    if not exclude:
        exclude = ['onidc', 'slug', 'created', 'modified']
    exclude.extend([f.name for f in opts.fields if getattr(f, 'choices')])
    fields = []
    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):
            fields.append(f.name + '__icontains')
    return fields 
Example 4
def get_migrations_for_django_21_and_newer():
    return [
        # remove primary key information from 'key' field
        migrations.AlterField(
            model_name='resetpasswordtoken',
            name='key',
            field=models.CharField(db_index=True, primary_key=False, max_length=64, unique=True, verbose_name='Key'),
        ),
        # add a new id field
        migrations.AddField(
            model_name='resetpasswordtoken',
            name='id',
            field=models.AutoField(primary_key=True, serialize=False),
            preserve_default=False,
        ),
        migrations.RunPython(
            populate_auto_incrementing_pk_field,
            migrations.RunPython.noop
        ),
    ] 
Example 5
Project: sphinxcontrib-django   Author: edoburu   File: test_docstrings.py    License: Apache License 2.0 6 votes vote down vote up
def test_model_init_params(self):
        """Model __init__ gets all fields as params."""
        lines = []
        docstrings._add_model_fields_as_params(self.app, SimpleModel, lines)
        self.assertEqual(
            lines,
            [
                ":param id: Id",
                ":type id: AutoField",
                ":param user: User",
                ":type user: ForeignKey to :class:`~django.contrib.auth.models.User`",
                ":param user2: User2",
                ":type user2: ForeignKey to"
                " :class:`~sphinxcontrib_django.tests.test_docstrings.User2`",
                ":param user3: User3",
                ":type user3: ForeignKey to :class:`~django.contrib.auth.models.User`",
                ":param dummy_field: Dummy field",
                ":type dummy_field: CharField",
            ],
        ) 
Example 6
Project: sphinxcontrib-django   Author: edoburu   File: test_docstrings.py    License: Apache License 2.0 6 votes vote down vote up
def test_add_form_fields(self):
        """Form fields should be mentioned."""
        lines = []
        docstrings._add_form_fields(SimpleForm, lines)
        self.assertEqual(
            lines,
            [
                "**Form fields:**",
                "",
                "* ``user``: User (:class:`~django.forms.models.ModelChoiceField`)",
                "* ``user2``: User2 (:class:`~django.forms.models.ModelChoiceField`)",
                "* ``user3``: User3 (:class:`~django.forms.models.ModelChoiceField`)",
                "* ``test1``: Test1 (:class:`~django.forms.fields.CharField`)",
                "* ``test2``: Test2 (:class:`~django.forms.fields.CharField`)",
            ],
        ) 
Example 7
Project: django-ra-erp   Author: ra-systems   File: models.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get_redirect_url_prefix(cls):
        """
        Get the url for the change list of this model
        :return: a string url
        """
        return reverse('%s:%s_%s_changelist' % (
            app_settings.RA_ADMIN_SITE_NAME, cls._meta.app_label, cls.get_class_name().lower()))


# class BasePersonInfo(BaseInfo):
#     address = models.CharField(_('address'), max_length=260, null=True, blank=True)
#     telephone = models.CharField(_('telephone'), max_length=130, null=True, blank=True)
#     email = models.EmailField(_('email'), null=True, blank=True)
#
#     class Meta:
#         abstract = True
#         # swappable = swapper.swappable_setting('ra', 'BasePersonInfo') 
Example 8
Project: byro   Author: byro   File: registration.py    License: Apache License 2.0 6 votes vote down vote up
def build_default_field(self, field, model):
        choices = getattr(field, "choices", None)
        if choices:
            return forms.ChoiceField(
                required=False,
                label=_("Default value"),
                choices=[(None, "-----------")] + list(choices),
            )
        if not (model is Member and field.name == "number"):
            if isinstance(field, models.CharField):
                return forms.CharField(required=False, label=_("Default value"))
            elif isinstance(field, models.DecimalField):
                return forms.DecimalField(
                    required=False,
                    label=_("Default value"),
                    max_digits=field.max_digits,
                    decimal_places=field.decimal_places,
                )
            elif isinstance(field, models.DateField):
                return forms.CharField(required=False, label=_("Other/fixed date")) 
Example 9
Project: django-localized-fields   Author: SectorLabs   File: test_slug_fields.py    License: MIT License 6 votes vote down vote up
def test_populate_multiple_from_fields():
        """Tests whether populating the slug from multiple fields works
        correctly."""

        model = get_fake_model(
            {
                "title": LocalizedField(),
                "name": models.CharField(max_length=255),
                "slug": LocalizedUniqueSlugField(
                    populate_from=("title", "name")
                ),
            }
        )

        obj = model()
        for lang_code, lang_name in settings.LANGUAGES:
            obj.name = "swen"
            obj.title.set(lang_code, "title %s" % lang_name)

        obj.save()

        for lang_code, lang_name in settings.LANGUAGES:
            assert (
                obj.slug.get(lang_code) == "title-%s-swen" % lang_name.lower()
            ) 
Example 10
Project: django-localized-fields   Author: SectorLabs   File: test_expressions.py    License: MIT License 6 votes vote down vote up
def setUpClass(cls):
        """Creates the test model in the database."""

        super(LocalizedExpressionsTestCase, cls).setUpClass()

        cls.TestModel1 = get_fake_model(
            {"name": models.CharField(null=False, blank=False, max_length=255)}
        )

        cls.TestModel2 = get_fake_model(
            {
                "text": LocalizedField(),
                "other": models.ForeignKey(
                    cls.TestModel1,
                    related_name="features",
                    on_delete=models.CASCADE,
                ),
            }
        ) 
Example 11
Project: django-leonardo   Author: django-leonardo   File: admin.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def owner_search_fields(self):
        """
        Returns all the fields that are CharFields except for password from the
        User model.  For the built-in User model, that means username,
        first_name, last_name, and email.
        """
        try:
            from django.contrib.auth import get_user_model
        except ImportError:  # Django < 1.5
            from django.contrib.auth.models import User
        else:
            User = get_user_model()
        return [
            field.name for field in User._meta.fields
            if isinstance(field, models.CharField) and field.name != 'password'
        ] 
Example 12
Project: django-river   Author: javrasya   File: orm_driver.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_available_approvals(self, as_user):
        those_with_max_priority = With(
            TransitionApproval.objects.filter(
                workflow=self.workflow, status=PENDING
            ).values(
                'workflow', 'object_id', 'transition'
            ).annotate(min_priority=Min('priority'))
        )

        workflow_objects = With(
            self.wokflow_object_class.objects.all(),
            name="workflow_object"
        )

        approvals_with_max_priority = those_with_max_priority.join(
            self._authorized_approvals(as_user),
            workflow_id=those_with_max_priority.col.workflow_id,
            object_id=those_with_max_priority.col.object_id,
            transition_id=those_with_max_priority.col.transition_id,
        ).with_cte(
            those_with_max_priority
        ).annotate(
            object_id_as_str=Cast('object_id', CharField(max_length=200)),
            min_priority=those_with_max_priority.col.min_priority
        ).filter(min_priority=F("priority"))

        return workflow_objects.join(
            approvals_with_max_priority, object_id_as_str=Cast(workflow_objects.col.pk, CharField(max_length=200))
        ).with_cte(
            workflow_objects
        ).filter(transition__source_state=getattr(workflow_objects.col, self.field_name + "_id")) 
Example 13
Project: django-accounting   Author: dulacp   File: fields.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        kwargs['max_length'] = kwargs.get('max_length', 64 )
        kwargs['blank'] = True
        models.CharField.__init__(self, *args, **kwargs) 
Example 14
Project: django-accounting   Author: dulacp   File: fields.py    License: MIT License 5 votes vote down vote up
def pre_save(self, model_instance, add):
        if add or not getattr(model_instance, self.attname):
            value = self._generate_uuid()
            setattr(model_instance, self.attname, value)
            return value
        else:
            return super(models.CharField, self).pre_save(model_instance, add) 
Example 15
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 16
Project: python-mysql-pool   Author: LuciferJack   File: validation.py    License: MIT License 5 votes vote down vote up
def validate_field(self, errors, opts, f):
            """
            MySQL has the following field length restriction:
            No character (varchar) fields can have a length exceeding 255
            characters if they have a unique index on them.
            """
            varchar_fields = (models.CharField,
                              models.CommaSeparatedIntegerField,
                              models.SlugField)
            if isinstance(f, varchar_fields) and f.max_length > 255 and f.unique:
                msg = ('"%(name)s": %(cls)s cannot have a "max_length" greater '
                       'than 255 when using "unique=True".')
                errors.add(opts, msg % {'name': f.name,
                                        'cls': f.__class__.__name__}) 
Example 17
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 18
Project: django-idcops   Author: Wenvki   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def nature_field_name(model):
    """ Return model CharField , SlugField Field name use nature field."""
    opts = model._meta
    fields = [
        f.name for f in opts.fields if (
            isinstance(f, models.CharField)
            and not getattr(f, 'blank', False)
        )
    ]
    if fields:
        if 'name' in fields:
            return 'name'
        elif 'text' in fields:
            return 'text'
        elif 'title' in fields:
            return 'title'
        elif 'username' in fields:
            return 'username'
        elif 'linenum' in fields:
            return 'linenum'
        elif 'kcnum' in fields:
            return 'kcnum'
        else:
            if 'created' in [f.name for f in opts.fields]:
                return 'created'
            else:
                return fields[0]
    else:
        if 'created' in [f.name for f in opts.get_fields()]:
            return 'created'
        else:
            return '{}'.format(opts.pk.attname) 
Example 19
Project: django-idcops   Author: Wenvki   File: tasks.py    License: Apache License 2.0 5 votes vote down vote up
def get_related_client_name(obj):
    related_clients = []
    for f in obj._meta.fields:
        if f.related_model is Client or (
                f.name == 'client' and isinstance(f, models.CharField)):
            value = display_for_field(f.value_from_object(obj), f, html=False)
            related_clients.append(value)
    return '{}'.format(", ".join(c for c in list(set(related_clients)))) 
Example 20
Project: django-angularjs-blog   Author: bluedazzle   File: test_Serializer.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def setUp(self):
        self.time_func = TimeFormatFactory.get_time_func('string')
        # DATABASES = {
        #     'default': {
        #     'ENGINE': 'django.db.backends.sqlite3',
        #     'NAME': ':memory:',
        #     'USER': '',                      # Not used with sqlite3.
        #     'PASSWORD': '',                  # Not used with sqlite3.
        #     'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        #     'PORT': '',
        #     }
        # }
        # settings.configure(DATABASES=DATABASES, DEBUG=True)
        # class TestAuthor(models.Model):
        #     name = models.CharField(default='test_author')
        #
        #     def __unicode__(self):
        #         return self.name
        #
        # class TestTags(models.Model):
        #     tag = models.CharField(default='test_tag')
        #     create_time = models.DateTimeField(auto_now=True)
        #
        # class TestArticle(models.Model):
        #     title = models.CharField(default='test')
        #     content = models.CharField(default='test')
        #     author = models.ForeignKey(TestAuthor, related_name='author_art')
        #     tags = models.ManyToManyField(TestTags, related_name='tag_art')
        #     create_time = models.DateTimeField(auto_now=True)
        #
        #
        # self.author = TestAuthor()
        # self.author.save()
        # tags = TestTags(tag='tag1')
        # tags.save()
        # self.article = TestArticle(author=self.author)
        # self.article.tags.add(tags)
        # self.article.save() 
Example 21
Project: GTDWeb   Author: lanbing510   File: models.py    License: GNU General Public License v2.0 5 votes vote down vote up
def add_spatial_version_related_fields(sender, **kwargs):
    """
    Adds fields after establishing a database connection to prevent database
    operations at compile time.
    """
    if connection_created.disconnect(add_spatial_version_related_fields, sender=DatabaseWrapper):
        spatial_version = connection.ops.spatial_version[0]
        if spatial_version >= 4:
            SpatialiteSpatialRefSys.add_to_class('srtext', models.CharField(max_length=2048))
            SpatialiteGeometryColumns.add_to_class('type', models.IntegerField(db_column='geometry_type'))
        else:
            SpatialiteGeometryColumns.add_to_class('type', models.CharField(max_length=30)) 
Example 22
Project: django-cryptography   Author: georgemarshall   File: test_encrypted.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_field_checks(self):
        class BadField(models.Model):
            field = encrypt(models.CharField())

            class Meta:
                app_label = 'myapp'

        model = BadField()
        errors = model.check()
        self.assertEqual(len(errors), 1)
        # The inner CharField is missing a max_length.
        self.assertEqual('fields.E120', errors[0].id)
        self.assertIn('max_length', errors[0].msg) 
Example 23
Project: django-cryptography   Author: georgemarshall   File: test_encrypted.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_deconstruct_args(self):
        field = encrypt(models.CharField(max_length=20))
        name, path, args, kwargs = field.deconstruct()
        new = encrypt(*args, **kwargs)
        self.assertEqual(new.max_length, field.max_length) 
Example 24
Project: django-cryptography   Author: georgemarshall   File: test_encrypted.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_model_field_formfield(self):
        model_field = encrypt(models.CharField(max_length=27))
        form_field = model_field.formfield()
        self.assertIsInstance(form_field, forms.CharField)
        self.assertEqual(form_field.max_length, 27) 
Example 25
Project: dingtalk-django-example   Author: 007gzs   File: model.py    License: GNU General Public License v3.0 5 votes vote down vote up
def ex_search_fields(cls):
        ret = set()
        for field in cls._meta.fields:
            if not field.db_index and not field.unique \
                    and field.name == 'name' and isinstance(field, models.CharField):
                ret.add(field.name)
        return ret 
Example 26
Project: aswan   Author: momosecurity   File: models.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_hit_log_model(db_table):
    class CustomMetaClass(ModelBase):
        def __new__(cls, name, bases, attrs):
            model = super(CustomMetaClass, cls).__new__(cls, name, bases,
                                                        attrs)
            model._meta.db_table = db_table
            model._meta.index_together = (
                ('time',),
                ('user_id',),
            )
            model.managed = False
            return model

    class HitLogModel(models.Model, metaclass=CustomMetaClass):
        time = models.DateTimeField(verbose_name=_(u'命中时间'))
        rule_id = models.IntegerField(verbose_name=_(u'规则ID'))
        user_id = models.IntegerField(verbose_name=_(u'命中用户'))
        kwargs = models.CharField(max_length=128, null=False, default='', verbose_name=_(u'扩展参数'))
        req_body = models.CharField(max_length=512, null=False, default='', verbose_name=_(u'请求参数'))
        control = models.CharField(max_length=16, null=False, default='', verbose_name=_(u'管控原子'))
        custom = models.CharField(max_length=50, null=False, default='', verbose_name=_(u'策略组解释'))
        group_name = models.CharField(max_length=256, null=False, default='',
                                      verbose_name=_(u'策略原子组名称'))
        group_uuid = models.CharField(max_length=36, null=False, default='',
                                      verbose_name=_(u'策略原子组UUID'))
        hit_number = models.PositiveSmallIntegerField(null=False, default=1, verbose_name=_(u'命中次序'))

        objects = Manager()

    return HitLogModel 
Example 27
Project: koku   Author: project-koku   File: helpers.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _populate_storage_daily_table(self):
        """Populate the daily table."""
        included_fields = [
            "namespace",
            "pod",
            "report_period_id",
            "persistentvolumeclaim",
            "persistentvolume",
            "storageclass",
            "persistentvolume_labels",
            "persistentvolumeclaim_labels",
        ]
        annotations = {
            "node": Value(random.choice(self.line_items).get("node"), output_field=CharField()),
            "usage_start": F("report__interval_start"),
            "usage_end": F("report__interval_start"),
            "persistentvolumeclaim_capacity_bytes": Max("persistentvolumeclaim_capacity_bytes"),
            "persistentvolumeclaim_capacity_byte_seconds": Sum("persistentvolumeclaim_capacity_byte_seconds"),
            "volume_request_storage_byte_seconds": Sum("volume_request_storage_byte_seconds"),
            "persistentvolumeclaim_usage_byte_seconds": Sum("persistentvolumeclaim_usage_byte_seconds"),
            "cluster_id": F("report_period__cluster_id"),
            "cluster_alias": Value(self.cluster_alias, output_field=CharField()),
        }
        entries = OCPStorageLineItem.objects.values(*included_fields).annotate(**annotations)

        for entry in entries:
            entry["total_seconds"] = 3600
            daily = OCPStorageLineItemDaily(**entry)
            daily.save() 
Example 28
Project: koku   Author: project-koku   File: helpers.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _populate_storage_daily_summary_table(self):
        """Populate the daily summary table."""
        included_fields = [
            "usage_start",
            "usage_end",
            "namespace",
            "report_period_id",
            "pod",
            "node",
            "persistentvolumeclaim",
            "persistentvolume",
            "storageclass",
            "cluster_id",
            "cluster_alias",
        ]
        annotations = {
            "volume_labels": Coalesce(F("persistentvolume_labels"), F("persistentvolumeclaim_labels")),
            "persistentvolumeclaim_capacity_gigabyte": ExpressionWrapper(
                F("persistentvolumeclaim_capacity_bytes") * math.pow(2, -30), output_field=DecimalField()
            ),
            "persistentvolumeclaim_capacity_gigabyte_months": ExpressionWrapper(
                F("persistentvolumeclaim_capacity_byte_seconds") / 86400 * 30 * math.pow(2, -30),
                output_field=DecimalField(),
            ),
            "volume_request_storage_gigabyte_months": ExpressionWrapper(
                F("volume_request_storage_byte_seconds") / 86400 * 30 * math.pow(2, -30), output_field=DecimalField()
            ),
            "persistentvolumeclaim_usage_gigabyte_months": ExpressionWrapper(
                F("persistentvolumeclaim_usage_byte_seconds") / 86400 * 30 * math.pow(2, -30),
                output_field=DecimalField(),
            ),
            "data_source": Value("Storage", output_field=CharField()),
        }

        entries = OCPStorageLineItemDaily.objects.values(*included_fields).annotate(**annotations)

        for entry in entries:
            summary = OCPUsageLineItemDailySummary(**entry)
            summary.save() 
Example 29
Project: koku   Author: project-koku   File: helpers.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _populate_node_label_daily_table(self):
        """Populate the daily table."""
        included_fields = ["node", "report_period_id", "node_labels"]
        annotations = {
            "usage_start": F("report__interval_start"),
            "usage_end": F("report__interval_start"),
            "cluster_id": F("report_period__cluster_id"),
            "cluster_alias": Value(self.cluster_alias, output_field=CharField()),
        }
        entries = OCPNodeLabelLineItem.objects.values(*included_fields).annotate(**annotations)

        for entry in entries:
            entry["total_seconds"] = 3600
            daily = OCPNodeLabelLineItemDaily(**entry)
            daily.save() 
Example 30
Project: kobo-predict   Author: awemulya   File: country_field.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_internal_type(self):
        return "CharField"