我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.db.models.TextField()。
def clean(self): strip_types = (models.CharField, models.TextField, models.URLField, models.EmailField, models.IPAddressField, models.GenericIPAddressField, models.SlugField) for field in self._meta.fields: # TODO: hardcode 'notes' here if not (field.name is 'notes') and isinstance(field, strip_types): value = getattr(self, field.name) if value: setattr(self, field.name, value.replace('\t', ' ').replace('\n', ' ').replace('\r', ' '))
def instantiate_object_id_field(object_id_class_or_tuple=models.TextField): """ Instantiates and returns a model field for FieldHistory.object_id. object_id_class_or_tuple may be either a Django model field class or a tuple of (model_field, kwargs), where kwargs is a dict passed to model_field's constructor. """ if isinstance(object_id_class_or_tuple, (list, tuple)): object_id_class, object_id_kwargs = object_id_class_or_tuple else: object_id_class = object_id_class_or_tuple object_id_kwargs = {} if not issubclass(object_id_class, models.fields.Field): raise TypeError('settings.%s must be a Django model field or (field, kwargs) tuple' % OBJECT_ID_TYPE_SETTING) if not isinstance(object_id_kwargs, dict): raise TypeError('settings.%s kwargs must be a dict' % OBJECT_ID_TYPE_SETTING) return object_id_class(db_index=True, **object_id_kwargs)
def __str__(self): return self.caption # class Cpu(models.Model): # # host = models.OneToOneField('Host') ???? # server = models.ForeignKey('Host') # cpu_model = models.CharField(verbose_name='CPU??', max_length=128,null=True) # cpu_count = models.SmallIntegerField(verbose_name='??CPU??',null=True) # cpu_core_count = models.SmallIntegerField(verbose_name='CPU???',null=True) # use = models.CharField(verbose_name='???',max_length=32,null=True) # memo = models.TextField(verbose_name='??', null=True,) # create_date = models.DateTimeField(auto_now_add=True, verbose_name='????') # update_date = models.DateTimeField(auto_now=True, null=True, verbose_name='????') # # class Meta: # db_table = 'Cpu' # verbose_name = 'CPU??' # verbose_name_plural = verbose_name # # unique_together=("host","cpu_model") ???? # # def __str__(self): # return self.cpu_model
def setUp(self): class TextDocument(models.Model): body = models.TextField() other = models.TextField() search = SearchVectorField([ WeightedColumn('body', 'D'), ], 'english') class TextDocumentLanguageColumn(models.Model): body = models.TextField() lang = models.TextField(null=True) search = SearchVectorField([ WeightedColumn('body', 'D'), ], language_column='lang', language='english') with DatabaseSchemaEditor(connection) as schema_editor: schema_editor.create_model(TextDocument) schema_editor.create_model(TextDocumentLanguageColumn) self.create = TextDocument.objects.create self.lang = TextDocumentLanguageColumn.objects.create
def setUp(self): class TextDocument(models.Model): title = models.CharField(max_length=128) body = models.TextField() search = SearchVectorField([ WeightedColumn('title', 'A'), WeightedColumn('body', 'D'), ], 'english') with DatabaseSchemaEditor(connection) as schema_editor: schema_editor.create_model(TextDocument) TextDocument.objects.create( title="My hovercraft is full of eels.", body="Spam! Spam! Spam! Spam! Spam! Spam!", ) TextDocument.objects.create( title="Spam! Spam! Spam! Spam! Spam! Spam!", body="My hovercraft is full of eels." ) self.objects = TextDocument.objects
def _categorization_translated_fields(): return TranslatedFields( name=models.CharField( _('Name'), max_length=128, ), slug=models.SlugField( _('Slug'), db_index=True, ), description=models.TextField( _('Description'), blank=True, help_text=_("Description of a categorization, usually used as lead text in categorization's detail view."), ), meta={ 'unique_together': [('language_code', 'slug')], }, )
def inbox_count_for(user): """ returns the number of unread messages for the given user but does not mark them seen """ return Message.objects.filter(recipient=user, read_at__isnull=True, recipient_deleted_at__isnull=True).count() # class GroupMessage(models.Model): # subject = models.CharField(_("Subject"), max_length=120) # body = models.TextField(_("Body")) # sender = models.ForeignKey(AUTH_USER_MODEL, related_name='sent_messages', verbose_name=_("Sender")) # recipient = models.ForeignKey(AUTH_USER_MODEL, related_name='received_messages', null=True, blank=True, verbose_name=_("Recipient")) # sent_at = models.DateTimeField(_("sent at"), null=True, blank=True) # objects = MessageManager() # class Meta: # ordering = ['-sent_at'] # verbose_name = _("GroupMessage") # verbose_name_plural = _("GroupMessages") # fallback for email notification if django-notification could not be found
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()
def types_text(self): return self.filter(type='TextField')
def __init__(self, *args, **kwargs): super(SimpleMdeField, self).__init__(*args, **kwargs) # using SimpleMdeWidget for TextField self.widget = SimpleMdeWidget()
def output_field(self): return TextField()
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) )
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)
def test_object_id_field_type_requires_kwargs_as_dict(self): object_id_tuple_bad_kwargs = (models.TextField, 10) self.assertRaises(TypeError, lambda: instantiate_object_id_field(object_id_tuple_bad_kwargs))
def get_queryset(self, request): qs = super(CommentAdmin, self).get_queryset(request) if django.VERSION >= (1, 8): # Concat is not available in 1.7 and 1.6 qs = qs.annotate(author_sort=Concat('author_type', 'author_id', output_field=TextField())) qs = qs.annotate(page_sort=Concat('page_type', 'page_id', output_field=TextField())) return qs
def diff_field(self, name, old, new, **kwargs): old_val = getattr(old, name, None) new_val = getattr(new, name, None) if old_val == new_val: return None try: field = self.model._meta.get_field(name) except models.FieldDoesNotExist: field = None if isinstance(field, models.ForeignKey): return diff_model_instances(old_val, new_val, model=field.rel.to, **kwargs) elif isinstance(new_val, (Manager, QuerySet)) or isinstance(old_val, (Manager, QuerySet)): old_val = list(old_val.all()) if old else [] new_val = list(new_val.all()) if new else [] if not old_val and not new_val: return None return ListDiffNode(old_val, new_val, **kwargs) elif field is not None and field.choices: old_val = str(dict(field.choices)[old_val]) if old_val else _('No Information') new_val = str(dict(field.choices)[new_val]) if new_val else _('No Information') return AtomicDiffNode(old_val, new_val, **kwargs) elif isinstance(field, (models.CharField, models.TextField)) and old_val and new_val: return TextDiffNode(old_val, new_val, **kwargs) else: return AtomicDiffNode(_render_value(old_val), _render_value(new_val), **kwargs)
def get_field_style(self, attrs, db_field, style, **kwargs): if style == 'ueditor': if isinstance(db_field, UEditorField): widget = db_field.formfield().widget param = {} param.update(widget.ueditor_settings) param.update(widget.attrs) return {'widget': XadminUEditorWidget(**param)} if isinstance(db_field, TextField): return {'widget': XadminUEditorWidget} return attrs
def get_field_cls(self, field): str_fields = (models.CharField, models.TextField, models.UUIDField) if isinstance(field, str_fields): return StrField elif isinstance(field, (models.AutoField, models.IntegerField)): return IntField elif isinstance(field, (models.BooleanField, models.NullBooleanField)): return BoolField elif isinstance(field, (models.DecimalField, models.FloatField)): return FloatField elif isinstance(field, models.DateTimeField): return DateTimeField elif isinstance(field, models.DateField): return DateField return DjangoQLField
def test_should_text_convert_string(): assert_conversion(models.TextField, graphene.String)
def get_internal_type(self): return "TextField"
def test(cls, field, request, params, model, admin_view, field_path): return isinstance(field, models.CharField) or isinstance(field, models.TextField)
def test_obfuscate_return(self): self.assertEqual( ObfuscatorUtils.obfuscate(models.TextField(), 'unittest'), '26a824a52b35848551eb7fc48f552635170b52f9857f9f8cddcc0ae2')
def __init__(self, *args, **kwargs): warnings.warn("Django 1.9 features a native JsonField, this JSONField will " "be removed somewhere after Django 1.8 becomes unsupported.", DeprecationWarning) kwargs['default'] = kwargs.get('default', dict) models.TextField.__init__(self, *args, **kwargs)
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)
def field_needs_nullability_check(self, field): if isinstance(field, (models.CharField, models.TextField)): if field.blank and not field.null: return True return False # Deserialize JSON to Django Model objects. # obj: Model object to update (for PUT), newly created object (for POST) # values: Python dict of {field name: value} (parsed JSON) # Output: Python dict representation of the updated object
def _find_textual_columns(self): columns = [] # PostgreSQL trigger only has access to fields in the table, so we # need to make sure to exclude any fields from multi-table inheritance for field in self.model._meta.get_fields(include_parents=False): # too restrictive? if isinstance(field, (CharField, TextField)): columns.append(field.column) return columns
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)
def test_http_user_agent(self): field = ServeLog._meta.get_field('http_user_agent') self.assertModelField(field, models.TextField, True, False)
def get_translatable_content(self): """ Returns {field_name: field_contents} for translatable fields, where field_contents > '' """ fields = (f for f in self._meta.fields if isinstance(f, (models.CharField, models.TextField)) and f.editable and not f.choices and f.name not in self.translatable_content_excluded_fields) return dict(filter(itemgetter(1), ((f.name, getattr(self, f.name)) for f in fields)))
def contribute_to_class(self, cls, name): if self.auto_create_html_field and not cls._meta.abstract: self.html_field = models.TextField(editable=False, blank=True) self.html_field.creation_counter = self.creation_counter + 1 cls.add_to_class('_{}_html'.format(name), self.html_field) super(PandocField, self).contribute_to_class(cls, name) setattr(cls, name, self)
def clean(self): """ Cleans white space from CharFields and TextFields """ for field in self._meta.fields: if isinstance(field, (models.CharField, models.TextField)): value = getattr(self, field.name) if value: setattr(self, field.name, value.strip())
def create_news_abc(schedule_model): """Abstract base news model factory. :param schedule_model: Schedule model to use as news's schedule. :type schedule_model: Any concrete schedule model of abc models from :func:`~create_abc_schedule` factory function. :returns: A abstract base news model. :rtype: Abstract base django model of :class:`~news.models.AbstractNews` implementation """ class AbstractBaseNews(models.Model, AbstractNews): schedule = models.ForeignKey( schedule_model, related_name='news_list', db_index=True ) parent = models.ForeignKey( 'self', related_name='children', db_index=True, blank=True, null=True ) url = models.URLField() author = models.CharField(max_length=AUTHOR_MAX_LENGTH, null=True) title = models.CharField(max_length=TITLE_MAX_LENGTH) summary = models.TextField() content = models.TextField() image = models.URLField(null=True) published = models.DateTimeField(blank=True, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: abstract = True unique_together = (('schedule', 'url'),) return AbstractBaseNews
def __str__(self): return self.title # ?????????? TextField? # ????????????? CharField? # ???????????????????? # ???? TextField ????????
def test_help_text_field(self): """ The model should have a help_text field """ field = OmniField._meta.get_field('help_text') self.assertIsInstance(field, models.TextField) self.assertTrue(field.blank) self.assertTrue(field.null)
def test_initial(self): """ The model should have an initial field """ field = OmniCharField._meta.get_field('initial') self.assertIsInstance(field, models.TextField) self.assertTrue(field.blank) self.assertTrue(field.null)
def test_recipients_field(self): """ The model should define a recipients field """ field = OmniFormEmailHandler._meta.get_field('recipients') self.assertIsInstance(field, models.TextField) self.assertFalse(field.blank) self.assertFalse(field.null)
def test_template_field(self): """ The model should define a template field """ field = OmniFormEmailHandler._meta.get_field('template') self.assertIsInstance(field, models.TextField) self.assertFalse(field.blank) self.assertFalse(field.null)
def get_concrete_class_for_model_field(cls, model_field): """ Method for getting a concrete model class to represent the type of form field required :param model_field: Model Field instance :return: OmniField subclass """ field_mapping = { models.CharField: OmniCharField, models.TextField: OmniCharField, models.BooleanField: OmniBooleanField, models.NullBooleanField: OmniBooleanField, models.DateField: OmniDateField, models.DateTimeField: OmniDateTimeField, models.DecimalField: OmniDecimalField, models.EmailField: OmniEmailField, models.FloatField: OmniFloatField, models.IntegerField: OmniIntegerField, models.BigIntegerField: OmniIntegerField, models.PositiveIntegerField: OmniIntegerField, models.PositiveSmallIntegerField: OmniIntegerField, models.SmallIntegerField: OmniIntegerField, models.CommaSeparatedIntegerField: OmniCharField, models.TimeField: OmniTimeField, models.URLField: OmniUrlField, models.ForeignKey: OmniForeignKeyField, models.ManyToManyField: OmniManyToManyField, models.SlugField: OmniSlugField, models.FileField: OmniFileField, models.ImageField: OmniImageField, models.DurationField: OmniDurationField, models.GenericIPAddressField: OmniGenericIPAddressField } field_mapping.update(cls.get_custom_field_mapping()) return field_mapping.get(model_field.__class__)