Here are the examples of the python api django.db.models.CharField taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
135 Examples
3
Example 1
Project: localwiki-backend-server Source File: tests.py
def test_can_handle_any_field(self):
"""
Out of the box, the registry should offer diff utils for any field.
"""
r = self.registry
field_types = [db.models.CharField, db.models.TextField,
db.models.BooleanField]
for t in field_types:
d = r.get_diff_util(t)
self.assertTrue(issubclass(d, BaseFieldDiff))
3
Example 2
def test_percents_in_defaults(self):
"""
Test that % in a default gets escaped to %%.
"""
cursor = connection.cursor()
try:
db.create_table("testpind", [('cf', models.CharField(max_length=255, default="It should be 2%!"))])
except IndexError:
self.fail("% was not properly escaped in column SQL.")
db.delete_table("testpind")
3
Example 3
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)
3
Example 4
def to_python(self, value):
if isinstance(value, models.CharField):
return value
if value == None:
return ""
else:
return value
3
Example 5
Project: django-scrape Source File: items.py
def get_field_query(item, field, value, pipeline, spider, use_null=False):
if value in ('', None, []):
if use_null:
if isinstance(field, (django_models.CharField, django_models.TextField)):
return ('', '')
else:
return ('__isnull', True)
else:
return None
value = get_field_value(item, field, value, pipeline, spider)
if isinstance(field, AddressField):
return ('', value)
elif isinstance(field, ManyToManyField):
return ('__contains', value)
elif isinstance(field, FileField):
return ('__contains', os.path.basename(value))
return ('', value)
3
Example 6
Project: django-cms Source File: test_extensions.py
def get_title_extension_class(self):
from django.db import models
class TestTitleExtension(TitleExtension):
content = models.CharField('Content', max_length=50)
class Meta:
abstract = True
return TestTitleExtension
3
Example 7
Project: django-firebird Source File: tests.py
def test_charfield_get_choices_doesnt_evaluate_lazy_strings(self):
# Regression test for #23098
# Will raise ZeroDivisionError if lazy is evaluated
lazy_func = lazy(lambda x: 0 / 0, int)
f = models.CharField(choices=[(lazy_func('group'), (('a', 'A'), ('b', 'B')))])
self.assertEqual(f.get_choices(True)[0], ('', '---------'))
3
Example 8
def __init__(self, expression, distinct=False, separator=None,
ordering=None, **extra):
if 'output_field' not in extra:
# This can/will be improved to SetTextField or ListTextField
extra['output_field'] = CharField()
super(GroupConcat, self).__init__(expression, **extra)
self.distinct = distinct
self.separator = separator
if ordering not in ('asc', 'desc', None):
raise ValueError(
"'ordering' must be one of 'asc', 'desc', or None")
self.ordering = ordering
3
Example 9
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__})
3
Example 10
def __init__(self, expression, regex, replace):
if not hasattr(regex, 'resolve_expression'):
regex = Value(regex)
if not hasattr(replace, 'resolve_expression'):
replace = Value(replace)
super(RegexpReplace, self).__init__(expression, regex, replace,
output_field=CharField())
3
Example 11
@classmethod
def initialize_type(cls, LAYOUT_CHOICES=None):
cls.add_to_class('layout', models.CharField(_('Layout'),
max_length=10, choices=LAYOUT_CHOICES,
default=LAYOUT_CHOICES[0][0]))
class ArticleCategoryListForm(ItemEditorForm):
layout = forms.ChoiceField(choices=LAYOUT_CHOICES,
initial=LAYOUT_CHOICES[0][0], label=_('Layout'),
widget=AdminRadioSelect(attrs={'class': 'radiolist'}))
cls.feincms_item_editor_form = ArticleCategoryListForm
cls.form = ArticleCategoryListForm
3
Example 12
def test_choices(self):
em = EasyModel(django_databrowse.site, SomeModel)
field = EasyField(
em,
models.CharField(max_length=2,
choices=(("a", "azerty"),("q","querty"))
)
)
self.assertEqual(len([f for f in field.choices()]), 2)
3
Example 13
Project: django-cms Source File: pluginmodel.py
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)))
3
Example 14
Project: django-any Source File: field_attr_choices.py
def test_choices_named_groups_support(self):
"""
Group names completely ignored
"""
MEDIA_CHOICES = (
('Audio', (
('vinyl', 'Vinyl'),
('cd', 'CD'),
)),
('Video', (
('vhs', 'VHS Tape'),
('dvd', 'DVD'),
)),
('unknown', 'Unknown'))
media = models.CharField(max_length=25, choices=MEDIA_CHOICES)
result = any_field(media)
self.assertTrue(result in ['vinyl', 'cd', 'vhs', 'dvd', 'unknown'])
3
Example 15
Project: transifex Source File: 0001_initial.py
def forwards(self, orm):
# Adding model 'Language'
db.create_table('translations_language', (
('code_aliases', models.CharField(_('Code aliases'), default='', max_length=100, null=True)),
('code', models.CharField(_('Code'), max_length=50, unique=True)),
('description', models.CharField(_('Description'), max_length=255, blank=True)),
('pluralequation', models.CharField(_("Plural Equation"), max_length=255, blank=True)),
('nplurals', models.SmallIntegerField(_("Number of Plurals"), default=0)),
('specialchars', models.CharField(_("Special Chars"), max_length=255, blank=True)),
('id', models.AutoField(primary_key=True)),
('name', models.CharField(_('Name'), max_length=50, unique=True)),
))
db.send_create_signal('languages', ['Language'])
3
Example 16
Project: towel Source File: forms.py
def towel_formfield_callback(field, **kwargs):
"""
Use this callback as ``formfield_callback`` if you want to use stripped
text inputs and textareas automatically without manually specifying the
widgets. Adds a ``dateinput`` class to date and datetime fields too.
"""
if isinstance(field, models.CharField) and not field.choices:
kwargs['widget'] = StrippedTextInput()
elif isinstance(field, models.TextField):
kwargs['widget'] = StrippedTextarea()
elif isinstance(field, models.DateTimeField):
kwargs['widget'] = forms.DateTimeInput(attrs={'class': 'dateinput'})
elif isinstance(field, models.DateField):
kwargs['widget'] = forms.DateInput(attrs={'class': 'dateinput'})
return field.formfield(**kwargs)
3
Example 17
@classmethod
def initialize_type(cls, TYPES=None):
TYPES = TYPES or cls.DEFAULT_TYPES
cls.FORMATTERS = dict((t[0], t[2]) for t in TYPES)
cls.TYPE_CHOICES = [(t[0], t[1]) for t in TYPES]
cls.add_to_class('type', models.CharField(_('type'), max_length=20,
choices=cls.TYPE_CHOICES,
default=cls.TYPE_CHOICES[0][0]))
cls.add_to_class('data', models.TextField(_('data'), blank=True))
3
Example 18
Project: django-url-filter Source File: test_django.py
def test_get_form_field_for_field(self):
fs = ModelFilterSet()
assert isinstance(fs._get_form_field_for_field(models.CharField()), forms.CharField)
assert isinstance(fs._get_form_field_for_field(models.AutoField()), forms.IntegerField)
assert isinstance(fs._get_form_field_for_field(models.FileField()), forms.CharField)
class TestField(models.Field):
def formfield(self, **kwargs):
return
with pytest.raises(SkipFilter):
fs._get_form_field_for_field(TestField())
3
Example 19
def formfield(self, **kwargs):
"""
Returns best form field to represent this model field
"""
defaults = {
'form_class': SimpleLanguageField,
'populate': self.populate,
}
defaults.update(kwargs)
return super(models.CharField, self).formfield(**defaults)
3
Example 20
Project: popcorn_maker Source File: db.py
def test_alter_char_default(self):
"""
Test altering column defaults with char fields
"""
db.create_table("test_altercd", [
('spam', models.CharField(max_length=30)),
('eggs', models.IntegerField()),
])
# Change spam default
db.alter_column("test_altercd", "spam", models.CharField(max_length=30, default="loof"))
3
Example 21
def get_content(self, obj):
"""Returns the search text for the page."""
content_obj = obj.content
return u" ".join((
super(PageSearchAdapter, self).get_content(obj),
self.prepare_content(u" ".join(
unicode(self._resolve_field(content_obj, field_name))
for field_name in (
field.name for field
in content_obj._meta.fields
if isinstance(field, (models.CharField, models.TextField))
)
))
))
3
Example 22
@classmethod
def initialize_type(cls, TYPE_CHOICES=None):
if TYPE_CHOICES is None:
raise ImproperlyConfigured(
'You have to set TYPE_CHOICES when'
' creating a %s' % cls.__name__)
cls.add_to_class(
'type',
models.CharField(
_('type'),
max_length=20,
choices=TYPE_CHOICES,
default=TYPE_CHOICES[0][0],
)
)
3
Example 23
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.
"""
from django.db import models
varchar_fields = (models.CharField, models.CommaSeparatedIntegerField,
models.SlugField)
if (isinstance(f, varchar_fields) and f.unique
and (f.max_length is None or int(f.max_length) > 255)):
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__})
3
Example 24
def set_value(self, dst, src, val):
field = self.model._meta.get_field_by_name(dst)[0]
if val is None and not field.null:
if field.blank and (isinstance(field, models.CharField) or isinstance(field, models.TextField)):
val = u""
else:
raise RowImportError(_(u"Null value not allowed for field '{src}'".format(src=src)))
if val == u"" and not field.blank:
raise RowImportError(_(u"Blank value not allowed for field '{src}'".format(src=src)))
setattr(self.obj, dst, val)
3
Example 25
def __init__(self, expression, regex):
if not hasattr(regex, 'resolve_expression'):
regex = Value(regex)
super(RegexpSubstr, self).__init__(expression, regex,
output_field=CharField())
3
Example 26
def __init__(self, model, field_name, regex):
self.regex = re.compile(regex.pattern, re.S | re.U | (regex.flags & re.I))
lookup_type = self.regex.flags & re.I and 'iregex' or 'regex'
super(ExtraFieldLookup, self).__init__(model, field_name,
lookup_type, ListField(models.CharField(max_length=256),
editable=False, null=True))
3
Example 27
def test_urls(self):
em = EasyModel(django_databrowse.site, SomeModel)
em.site.root_url = "root/"
field = EasyField(
em,
models.CharField(max_length=2,
choices=(("a", "azerty"),("q","querty")),
name="hello"
)
)
self.assertEqual(field.url(),
u'root/django_databrowse/somemodel/hello/')
em = EasyModel(django_databrowse.site, SomeInheritedModel)
field = EasyField(em, models.ForeignKey(SomeModel))
self.assertEqual(field.url(),
u'root/django_databrowse/someinheritedmodel/')
3
Example 28
def validate_field(self, errors, opts, f):
"Prior to MySQL 5.0.3, character fields could not exceed 255 characters"
from django.db import models
from django.db import connection
db_version = connection.get_server_version()
if db_version < (5, 0, 3) and isinstance(f, (models.CharField, models.CommaSeparatedIntegerField, models.SlugField)) and f.max_length > 255:
errors.add(opts,
'"%s": %s cannot have a "max_length" greater than 255 when you are using a version of MySQL prior to 5.0.3 (you are using %s).' %
(f.name, f.__class__.__name__, '.'.join([str(n) for n in db_version[:3]])))
3
Example 29
def contribute_to_class(self, cls, name):
if self.rendered_field and not cls._meta.abstract:
choices = zip([''] + self.markup_choices_list,
['--'] + self.markup_choices_title)
markup_type_field = models.CharField(
max_length=30,
choices=choices, default=self.default_markup_type,
editable=self.markup_type_editable,
blank=False if self.default_markup_type else True,
null=False if self.default_markup_type else True,
)
rendered_field = models.TextField(editable=False, null=self.null)
markup_type_field.creation_counter = self.creation_counter + 1
rendered_field.creation_counter = self.creation_counter + 2
cls.add_to_class(_markup_type_field_name(name), markup_type_field)
cls.add_to_class(_rendered_field_name(name), rendered_field)
super(MarkupField, self).contribute_to_class(cls, name)
setattr(cls, self.name, MarkupDescriptor(self))
3
Example 30
def forwards(self, orm):
db.create_table(u'content_featuretype', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=255)),
('slug', self.gf('django.db.models.fields.SlugField')(unique=True, max_length=50)),
))
db.send_create_signal(u'content', ['FeatureType'])
# Adding field 'Content.feature_type'
db.add_column(u'content_content', 'feature_type',
self.gf('django.db.models.fields.related.ForeignKey')(to=orm['content.FeatureType'], null=True, blank=True),
keep_default=False)
db.alter_column('content_content', 'feature_type', models.CharField(max_length=255, null=True, blank=True))
3
Example 31
Project: django-any Source File: models.py
@any_field.register(models.CharField)
def any_char_field(field, **kwargs):
"""
Return random value for CharField
>>> result = any_field(models.CharField(max_length=10))
>>> type(result)
<type 'str'>
"""
min_length = kwargs.get('min_length', 1)
max_length = kwargs.get('max_length', field.max_length)
return xunit.any_string(min_length=min_length, max_length=max_length)
3
Example 32
Project: django-cms Source File: test_extensions.py
def get_page_extension_class(self):
from django.db import models
class TestPageExtension(PageExtension):
content = models.CharField('Content', max_length=50)
class Meta:
abstract = True
return TestPageExtension
3
Example 33
Project: django-any Source File: test_custom_seed.py
@without_random_seed
@with_seed(1)
def test_deterministic_string(self):
media = models.CharField(max_length=25)
result = any_field(media)
self.assertEqual('SNnz', result)
3
Example 34
def formfield(self, **kwargs):
"""
Returns best form field to represent this model field
"""
defaults = {
'form_class': LanguageField,
'populate': self.populate,
}
defaults.update(kwargs)
return super(models.CharField, self).formfield(**defaults)
3
Example 35
Project: localwiki-backend-server Source File: tests.py
def test_register_field(self):
"""
If we register a fielddiff for a model, we should get that and not
BaseFieldDiff.
"""
self.registry.register(db.models.CharField, Diff_M1FieldDiff)
self.failUnlessEqual(self.registry.get_diff_util(db.models.CharField),
Diff_M1FieldDiff)
3
Example 36
@denormalized(models.CharField, max_length=255)
@depend_on_related('Member', foreign_key="author")
def author_name(self):
if self.author:
return self.author.name
else:
return ''
3
Example 37
Project: django-firebird Source File: tests.py
def test_choices_form_class(self):
"""Can supply a custom choices form class. Regression for #20999."""
choices = [('a', 'a')]
field = models.CharField(choices=choices)
klass = forms.TypedMultipleChoiceField
self.assertIsInstance(field.formfield(choices_form_class=klass), klass)
3
Example 38
def __init__(self, regpoint, enum_id, **kwargs):
"""
Class constructor.
"""
self.regpoint = regpoint
self.enum_id = enum_id
self._rp_choices = self.get_registered_choices().field_tuples()
kwargs['base_field'] = models.CharField(max_length=50, choices=self._rp_choices)
super(RegistryMultipleChoiceField, self).__init__(**kwargs)
3
Example 39
Project: django-firebird Source File: tests.py
def test_charfield_textfield_max_length_passed_to_formfield(self):
"""
Test that CharField and TextField pass their max_length attributes to
form fields created using their .formfield() method (#22206).
"""
cf1 = models.CharField()
cf2 = models.CharField(max_length=1234)
self.assertIsNone(cf1.formfield().max_length)
self.assertEqual(1234, cf2.formfield().max_length)
tf1 = models.TextField()
tf2 = models.TextField(max_length=2345)
self.assertIsNone(tf1.formfield().max_length)
self.assertEqual(2345, tf2.formfield().max_length)
3
Example 40
def __init__(self, *args, **kwargs):
defaults = {'new_lookup': 'startswith',
'field_to_add': ListField(models.CharField(500),
editable=False, null=True)
}
defaults.update(kwargs)
ExtraFieldLookup.__init__(self, *args, **defaults)
3
Example 41
def contribute_to_class(self, model, name):
super(MongoUserManager, self).contribute_to_class(model, name)
self.dj_model = self.model
self.model = get_user_docuement()
self.dj_model.USERNAME_FIELD = self.model.USERNAME_FIELD
username = CharField(_('username'), max_length=30, unique=True)
username.contribute_to_class(self.dj_model, self.dj_model.USERNAME_FIELD)
self.dj_model.REQUIRED_FIELDS = self.model.REQUIRED_FIELDS
for name in self.dj_model.REQUIRED_FIELDS:
field = CharField(_(name), max_length=30)
field.contribute_to_class(self.dj_model, name)
3
Example 42
def pre_save(self, model_instance, add):
if add :
value = str(uuid.uuid4())
setattr(model_instance, self.attname, value)
return value
else:
return super(models.CharField, self).pre_save(model_instance, add)
3
Example 43
def test_percents_in_defaults(self):
"""
Test that % in a default gets escaped to %%.
"""
try:
db.create_table("testpind", [('cf', models.CharField(max_length=255, default="It should be 2%!"))])
except IndexError:
self.fail("% was not properly escaped in column SQL.")
db.delete_table("testpind")
3
Example 44
def to_python(self, value):
if isinstance(value, models.CharField):
return value
if value is None:
return ''
return value
3
Example 45
def __init__(self, num, expressions):
value_exprs = []
for v in expressions:
if not hasattr(v, 'resolve_expression'):
v = Value(v)
value_exprs.append(v)
super(ELT, self).__init__(num, *value_exprs, output_field=CharField())
3
Example 46
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.
"""
from django.db import models
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__})
3
Example 47
Project: Django--an-app-at-a-time Source File: models.py
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))
3
Example 48
Project: django-fancypages Source File: base.py
def add_link_fields(cls):
if not getattr(cls, 'link_field_name', None):
cls.link_field_name = "link_url_%d"
for idx in range(1, cls.num_links + 1):
cls.add_to_class(
cls.link_field_name % idx,
models.CharField(_("Link URL %d" % idx), max_length=500,
blank=True, null=True))
3
Example 49
def forwards(self, orm):
db.alter_column('canvas_content', 'remix_of_id', models.CharField(max_length=40, blank=True, null=True))
db.alter_column('canvas_comment', 'parent_content_id', models.CharField(max_length=40))
db.alter_column('canvas_comment', 'reply_content_id', models.CharField(max_length=40, blank=True, null=True))
db.alter_column('canvas_contentsticker', 'content_id', models.CharField(max_length=40))
db.alter_column('canvas_stashcontent', 'content_id', models.CharField(max_length=40))
3
Example 50
def test_repr(self):
em = EasyModel(django_databrowse.site, SomeModel)
field = models.CharField(max_length=2, name="Hello")
value, label = "a", "azerty"
ec = EasyChoice(em, field, value, label)
self.assertEqual(ec.__repr__(), "<EasyChoice for SomeModel.Hello>")