Python django.db.models.fields 模块,CharField() 实例源码

我们从Python开源项目中,提取了以下12个代码示例,用于说明如何使用django.db.models.fields.CharField()

项目:tumanov_castleoaks    作者:Roamdev    | 项目源码 | 文件源码
def set_chars(instance, field, max_length=255):
    """ CharField """
    possibles = []
    possibles.extend(get_field_choices(field))
    if possibles:
        setattr(instance, field.name, random.choice(possibles))
        return

    max_length = min(max_length, field.max_length or 16 * 1024)
    for validator in field.validators:
        if isinstance(validator, MaxLengthValidator):
            max_length = min(max_length, validator.limit_value)

    value = generate_lorem_ipsum(1, min_len=1, max_len=max(5, max_length // 8), html=False)
    value = Truncator(value).chars(max_length, html=False)
    setattr(instance, field.name, value)
项目:Quiver-alfred    作者:danielecook    | 项目源码 | 文件源码
def get_django_field_map(self):
        from django.db.models import fields as djf
        return [
            (djf.AutoField, PrimaryKeyField),
            (djf.BigIntegerField, BigIntegerField),
            # (djf.BinaryField, BlobField),
            (djf.BooleanField, BooleanField),
            (djf.CharField, CharField),
            (djf.DateTimeField, DateTimeField),  # Extends DateField.
            (djf.DateField, DateField),
            (djf.DecimalField, DecimalField),
            (djf.FilePathField, CharField),
            (djf.FloatField, FloatField),
            (djf.IntegerField, IntegerField),
            (djf.NullBooleanField, partial(BooleanField, null=True)),
            (djf.TextField, TextField),
            (djf.TimeField, TimeField),
            (djf.related.ForeignKey, ForeignKeyField),
        ]
项目:metrics    作者:Jeremy-Friedman    | 项目源码 | 文件源码
def get_django_field_map(self):
        from django.db.models import fields as djf
        return [
            (djf.AutoField, PrimaryKeyField),
            (djf.BigIntegerField, BigIntegerField),
            # (djf.BinaryField, BlobField),
            (djf.BooleanField, BooleanField),
            (djf.CharField, CharField),
            (djf.DateTimeField, DateTimeField),  # Extends DateField.
            (djf.DateField, DateField),
            (djf.DecimalField, DecimalField),
            (djf.FilePathField, CharField),
            (djf.FloatField, FloatField),
            (djf.IntegerField, IntegerField),
            (djf.NullBooleanField, partial(BooleanField, null=True)),
            (djf.TextField, TextField),
            (djf.TimeField, TimeField),
            (djf.related.ForeignKey, ForeignKeyField),
        ]
项目:metrics    作者:Jeremy-Friedman    | 项目源码 | 文件源码
def get_django_field_map(self):
        from django.db.models import fields as djf
        return [
            (djf.AutoField, PrimaryKeyField),
            (djf.BigIntegerField, BigIntegerField),
            # (djf.BinaryField, BlobField),
            (djf.BooleanField, BooleanField),
            (djf.CharField, CharField),
            (djf.DateTimeField, DateTimeField),  # Extends DateField.
            (djf.DateField, DateField),
            (djf.DecimalField, DecimalField),
            (djf.FilePathField, CharField),
            (djf.FloatField, FloatField),
            (djf.IntegerField, IntegerField),
            (djf.NullBooleanField, partial(BooleanField, null=True)),
            (djf.TextField, TextField),
            (djf.TimeField, TimeField),
            (djf.related.ForeignKey, ForeignKeyField),
        ]
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def output_field(self):
        '''
        The type of field used to Cast/Coalesce to.

        Mainly because a max_length argument is required for CharField
        until this PR is merged: https://github.com/django/django/pull/8758
        '''
        Field = self.original_field.__class__
        if isinstance(self.original_field, fields.CharField):
            return Field(max_length=self.original_field.max_length)

        return Field()
项目:django-language-field    作者:audiolion    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        # Local import so the languages aren't loaded unless they are needed.
        from .languages import LANGUAGES

        kwargs.setdefault('max_length', 3)
        kwargs.setdefault('choices', LANGUAGES)
        super(CharField, self).__init__(*args, **kwargs)
项目:grical    作者:wikical    | 项目源码 | 文件源码
def get_internal_type(self):
        return 'CharField'
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def as_oracle(self, compiler, connection):
        # we can't mix TextField (NCLOB) and CharField (NVARCHAR), so convert
        # all fields to NCLOB when we expect NCLOB
        if self.output_field.get_internal_type() == 'TextField':
            class ToNCLOB(Func):
                function = 'TO_NCLOB'

            expressions = [
                ToNCLOB(expression) for expression in self.get_source_expressions()]
            clone = self.copy()
            clone.set_source_expressions(expressions)
            return super(Coalesce, clone).as_sql(compiler, connection)
        return self.as_sql(compiler, connection)
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def as_oracle(self, compiler, connection):
        # we can't mix TextField (NCLOB) and CharField (NVARCHAR), so convert
        # all fields to NCLOB when we expect NCLOB
        if self.output_field.get_internal_type() == 'TextField':
            class ToNCLOB(Func):
                function = 'TO_NCLOB'

            expressions = [
                ToNCLOB(expression) for expression in self.get_source_expressions()]
            clone = self.copy()
            clone.set_source_expressions(expressions)
            return super(Coalesce, clone).as_sql(compiler, connection)
        return self.as_sql(compiler, connection)
项目:elasticsearch-django    作者:yunojuno    | 项目源码 | 文件源码
def _raw_sql(self, values):
        """Prepare SQL statement consisting of a sequence of WHEN .. THEN statements."""
        if isinstance(self.model._meta.pk, CharField):
            when_clauses = ' '.join([self._when("'{}'".format(x), y) for (x, y) in values])
        else:
            when_clauses = ' '.join([self._when(x, y) for (x, y) in values])
        table_name = self.model._meta.db_table
        primary_key = self.model._meta.pk.column
        return 'SELECT CASE {}."{}" {} ELSE 0 END'.format(table_name, primary_key, when_clauses)
项目:LatinSounds_AppEnviaMail    作者:G3ek-aR    | 项目源码 | 文件源码
def as_oracle(self, compiler, connection):
        # we can't mix TextField (NCLOB) and CharField (NVARCHAR), so convert
        # all fields to NCLOB when we expect NCLOB
        if self.output_field.get_internal_type() == 'TextField':
            class ToNCLOB(Func):
                function = 'TO_NCLOB'

            expressions = [
                ToNCLOB(expression) for expression in self.get_source_expressions()]
            clone = self.copy()
            clone.set_source_expressions(expressions)
            return super(Coalesce, clone).as_sql(compiler, connection)
        return self.as_sql(compiler, connection)
项目:Django-ERP    作者:andyzsf    | 项目源码 | 文件源码
def export_selected_data(self,request,queryset):
        ops = self.model._meta
        workbook = xlwt.Workbook(encoding='utf-8')
        dd = datetime.date.today().strftime('%Y%m%d')
        file_name = force_text(ops.verbose_name+dd)
        sheet = workbook.add_sheet(force_text(ops.verbose_name))
        obj_fields = getattr(self,'export_fields',None) or self.list_display or self.fields

        head_col_index = 0
        for field in obj_fields:
            col_name = field
            try:
                f = ops.get_field(field)
                col_name = f.verbose_name
            except Exception,e:
                f = getattr(self.model,field)
                if hasattr(f,'short_description'):
                    col_name = f.short_description
            sheet.write(0,head_col_index,force_text(col_name))
            head_col_index+=1
        row_index = 1
        for obj in queryset:
            col_index = 0
            for field in obj_fields:
                f = field
                try:
                    f = ops.get_field(field)
                except Exception,e:
                    pass
                v = getattr(obj,field,'')
                if hasattr(v,'__call__') or callable(v):
                    v = v()
                elif type(f) == fields.DateField:
                    v = v.strftime('%Y-%m-%d')
                elif type(f) == fields.DateTimeField:
                    v = v.strftime('%Y-%m-%d %H:%M')
                elif type(f) == fields.CharField and f.choices:
                    fc = 'get_'+field+'_display'
                    v = getattr(obj,fc)()
                elif type(f) == related.ForeignKey:
                    v = str(v)
                sheet.write(row_index,col_index,v)
                col_index += 1
            row_index += 1
        response = HttpResponse(content_type='application/vnd.ms-excel')
        agent = request.META.get('HTTP_USER_AGENT')
        nn = smart_str(file_name)
        if agent and re.search('MSIE',agent):
            nn = urlquote(file_name)
        response['Content-Disposition'] = 'attachment; filename=%s.xls'%nn
        workbook.save(response)
        return response
        #self.message_user(request,'SUCCESS')