Here are the examples of the python api django.forms.CharField taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
166 Examples
3
Example 1
Project: django-mysql Source File: test_forms.py
def test_validators_fail_base_min_max_length(self):
# there's just no satisfying some people...
field = SimpleListField(forms.CharField(min_length=10, max_length=8))
with pytest.raises(exceptions.ValidationError) as excinfo:
field.clean('undefined')
assert (
excinfo.value.messages[0] ==
'Item 1 in the list did not validate: '
'Ensure this value has at least 10 characters (it has 9).'
)
assert (
excinfo.value.messages[1] ==
'Item 1 in the list did not validate: '
'Ensure this value has at most 8 characters (it has 9).'
)
3
Example 2
def __init__(self, *args, **kwargs):
self.temporary_data = kwargs.pop('temporary_data')
self.moderator = kwargs.pop('moderator')
super(CommentsForm, self).__init__(*args, **kwargs)
for field in self.temporary_data.comments.keys():
try:
help_text = _(u'La ciudadana dijo: %s') % self.temporary_data.data.get(field, u'')
except:
help_text = _(u'Ocurrió un problema sacando los datos')
comments = self.temporary_data.comments[field]
if comments:
help_text += _(u' <b>Y tus comentarios fueron: %s </b>') % comments
self.fields[field] = forms.CharField(required=False, help_text=help_text)
3
Example 3
Project: wagtail Source File: field_block.py
@cached_property
def field(self):
from wagtail.wagtailadmin.widgets import AdminAutoHeightTextInput
field_kwargs = {'widget': AdminAutoHeightTextInput(attrs={'rows': self.rows})}
field_kwargs.update(self.field_options)
return forms.CharField(**field_kwargs)
3
Example 4
def __init__(self, *args, **kwargs):
super(BookingIDAuthenticationForm, self).__init__(*args, **kwargs)
self.fields['username'] = forms.CharField(
label=_("Email"), max_length=256)
self.fields['password'] = forms.CharField(
label=_("Booking ID"), max_length=100)
3
Example 5
Project: django-html_sanitizer Source File: decorators.py
def actual_decorator(self, cls):
fields = [(key, value) for key, value in cls.base_fields.iteritems() if isinstance(value, forms.CharField)]
for field_name, field_object in fields:
original_clean = getattr(field_object, 'clean')
clean_func = get_sanitized_clean_func(original_clean, **self.kwargs)
setattr(field_object, 'clean', clean_func)
3
Example 6
def __init__(self, *args, **kwargs):
errors = self.default_error_messages.copy()
if 'error_messages' in kwargs:
errors.update(kwargs['error_messages'])
fields = (
forms.CharField(error_messages={'invalid': errors['invalid_time']}),
forms.CharField(error_messages={'invalid': errors['invalid_time']}),
)
super(SplitTimeField, self).__init__(fields, *args, **kwargs)
3
Example 7
Project: django-form-utils Source File: tests.py
def test_friendly_typo_error(self):
"""
If we define a single fieldset and leave off the trailing , in
a tuple, we get a friendly error.
"""
def _define_fieldsets_with_missing_comma():
class ErrorForm(BetterForm):
one = forms.CharField()
two = forms.CharField()
class Meta:
fieldsets = ((None, {'fields': ('one', 'two')}))
# can't test the message here, but it would be TypeError otherwise
self.assertRaises(ValueError,
_define_fieldsets_with_missing_comma)
3
Example 8
def make_entry_field(self, fieldsubmission=None):
from onlineforms.forms import ExplanationFieldWidget
w = ExplanationFieldWidget(attrs={'class': 'disabled', 'readonly': 'readonly'})
c = forms.CharField(required=False,
label=self.config['label'],
help_text='',
widget=w)
if 'text_explanation' in self.config:
w.explanation = self.config['text_explanation']
return c
3
Example 9
Project: django-rest-framework-braces Source File: test_serializer_form.py
@mock.patch.object(SerializerFormBase, 'get_serializer')
def test_clean_form_valid(self, mock_get_serializer):
class TestForm(SerializerFormBase):
hello = forms.CharField()
form = TestForm(data={'hello': 'world'})
mock_get_serializer.return_value.is_valid.return_value = True
mock_get_serializer.return_value.validated_data = {
'and': 'mars'
}
self.assertTrue(form.is_valid(), form.errors)
self.assertEqual(form.cleaned_data, {
'hello': 'world',
'and': 'mars',
})
3
Example 10
def __init__(self, *args, **kwargs):
super(RegistrationFormWithNames, self).__init__(*args, **kwargs)
adjust_username_field(self)
fields = self.fields.items()
fields[1:1] = [
('first_name', forms.CharField(label=_("First name"))),
('last_name', forms.CharField(label=_("Last name")))
]
self.fields = OrderedDict(fields)
3
Example 11
Project: zorna Source File: forms.py
def __init__(self, *args, **kwargs):
extra = kwargs.pop('extra')
request = kwargs.pop('request')
super(PageEditFileForm, self).__init__(*args, **kwargs)
ckeditor_config_name = SiteOptions.objects.get_ckeditor_config(request)
for b in extra:
self.fields['%s' % b['block']] = forms.CharField(
widget=CKEditorWidget(config_name=ckeditor_config_name), initial=b['content'])
3
Example 12
def autostrip(cls):
fields = [(key, value) for key, value in cls.base_fields.iteritems() if isinstance(value, forms.CharField)]
for field_name, field_object in fields:
def get_clean_func(original_clean):
return lambda value: original_clean(value and value.strip())
clean_func = get_clean_func(getattr(field_object, 'clean'))
setattr(field_object, 'clean', clean_func)
return cls
3
Example 13
Project: sponge Source File: repo.py
def extra_fields(self):
self.fields['parent_id'] = forms.CharField(widget=widgets.HiddenInput(),
initial=self.repo['id'],
required=False)
self.fields['clone_id'] = \
forms.CharField(label="Clone ID",
widget=CloneWidget(repo_utils.get_branch_id(self.repo)),
help_text="The repository ID of the ultimate ancestor of this repository will be automatically appended")
self.fields['clone_name'] = \
forms.CharField(label="Clone Name",
widget=CloneWidget(repo_utils.get_branch_name(self.repo), separator=': '),
help_text="The name of the ultimate ancestor of this repository will be automatically appended")
3
Example 14
def __init__(self, content_type, instance_pk, field_name, *args, **kwargs):
field_value = kwargs.pop('field_value', None)
if 'data' not in kwargs:
kwargs['prefix'] = '{0}:{1}:{2}'.format(content_type.pk, instance_pk, field_name)
super(FieldScribbleForm, self).__init__(*args, **kwargs)
self.content_type = content_type
self.instance_pk = instance_pk
self.field_name = field_name
self.fields['content'].initial = field_value
try:
self.fields['content'].required = not content_type.model_class()._meta.get_field(field_name).blank
except FieldDoesNotExist:
# Error will be caught on form validation
pass
self.fields[field_name] = forms.CharField(required=False)
3
Example 15
def __init__(self, config=None):
super(self.__class__, self).__init__(config)
self.config = config
if self.config:
keys = [c for c in self.config if c.startswith("choice_") and self.config[c]]
keys = sorted(keys, key=lambda choice: (int) (re.findall(r'\d+', choice)[0]))
else:
keys = []
for k in keys:
self.fields[k] = forms.CharField(required=False, label="Choice")
3
Example 16
Project: django-mysql Source File: test_listcharfield.py
def test_model_field_formfield(self):
model_field = ListCharField(models.CharField(max_length=27))
form_field = model_field.formfield()
assert isinstance(form_field, SimpleListField)
assert isinstance(form_field.base_field, forms.CharField)
assert form_field.base_field.max_length == 27
3
Example 17
Project: wagtail Source File: test_edit_handlers.py
def test_get_form_for_model(self):
EventPageForm = get_form_for_model(EventPage, form_class=WagtailAdminPageForm)
form = EventPageForm()
# form should be a subclass of WagtailAdminModelForm
self.assertTrue(issubclass(EventPageForm, WagtailAdminModelForm))
# form should contain a title field (from the base Page)
self.assertEqual(type(form.fields['title']), forms.CharField)
# and 'date_from' from EventPage
self.assertEqual(type(form.fields['date_from']), forms.DateField)
# the widget should be overridden with AdminDateInput as per FORM_FIELD_OVERRIDES
self.assertEqual(type(form.fields['date_from'].widget), AdminDateInput)
# treebeard's 'path' field should be excluded
self.assertNotIn('path', form.fields)
# all child relations become formsets by default
self.assertIn('speakers', form.formsets)
self.assertIn('related_links', form.formsets)
3
Example 18
Project: votainteligente-portal-electoral Source File: election_tags_based_search_tests.py
def test_it_has_a_field_named_q(self):
form = ElectionSearchByTagsForm()
self.assertIn('q', form.fields)
self.assertIsInstance(form.fields['q'], forms.CharField)
self.assertFalse(form.fields['q'].required)
self.assertEquals(form.fields['q'].label, _('Busca tu comuna'))
3
Example 19
def test_field_is_printed(self):
out = Template(
"{% load formstamps %}"
"{% stamp_regular_field field %}"
).render(Context({
'field': forms.CharField()
}))
self.assertIn('django.forms.fields.CharField object at', out)
3
Example 20
def formfield(self, **kwargs):
defaults = {
'form_class': forms.CharField,
'max_length': self.max_length,
}
defaults.update(kwargs)
return super(UUIDField, self).formfield(**defaults)
3
Example 21
def __init__(self, nplurals=1, attrs=None, textarea=True, *args, **kwargs):
self.widget = MultiStringWidget(nplurals=nplurals, attrs=attrs,
textarea=textarea)
self.hidden_widget = HiddenMultiStringWidget(nplurals=nplurals)
fields = [forms.CharField(strip=False) for i_ in range(nplurals)]
super(MultiStringFormField, self).__init__(fields=fields,
*args, **kwargs)
3
Example 22
def __init__(self, invitation=None, *args, **kwargs):
super(InvitationForm, self).__init__(*args, **kwargs)
self.fields['username'] = forms.CharField(
max_length=255, label=_("Username"))
self.fields['name'] = forms.CharField(
max_length=255, label=_("Your name"))
self.fields['password'] = forms.CharField(max_length=255, label=_("Password"),
widget=forms.PasswordInput(render_value=False))
self.fields['password_again'] = forms.CharField(max_length=255, label=_("Confirm Password"),
widget=forms.PasswordInput(render_value=False))
self.invitation = invitation
3
Example 23
def test_field_is_printed(self):
out = Template(
"{% load formstamps %}"
"{% stamp_inlineformset_field field %}"
).render(Context({
'field': forms.CharField()
}))
self.assertIn('django.forms.fields.CharField object at', out)
3
Example 24
Project: idea-color-themes Source File: forms.py
def __init__(self, button_type="buy", *args, **kwargs):
super(PayPalPaymentsForm, self).__init__(*args, **kwargs)
self.button_type = button_type
if 'initial' in kwargs:
# Dynamically create, so we can support everything PayPal does.
for k, v in kwargs['initial'].items():
if k not in self.base_fields:
self.fields[k] = forms.CharField(label=k, widget=ValueHiddenInput(), initial=v)
3
Example 25
def __init__(self, request, *args, **kwargs):
super(OISubmitSubmissionForm, self).__init__(request, *args, **kwargs)
self.fields['problem_shortname'] = \
forms.CharField(label=_("problem short name"))
self.fields['localtime'] = \
forms.DateTimeField(label=_("local time"), required=False)
self.fields['siotime'] = \
forms.DateTimeField(label=_("sio time"), required=False)
self.fields['magickey'] = \
forms.CharField(label=_("magic key"))
del self.fields['problem_instance_id']
3
Example 26
Project: zorna Source File: forms.py
def __init__(self, request, *args, **kwargs):
super(ZornaNoteForm, self).__init__(*args, **kwargs)
self.fields['category'].queryset = ZornaNoteCategory.tree.filter(
owner=request.user)
self.fields['content'] = forms.CharField(label=_(u'body'),
widget=CKEditorWidget(config_name=SiteOptions.objects.get_ckeditor_config(request)))
3
Example 27
def __init__(self, **kwargs):
self.instance = kwargs.pop('instance', None)
super(StepStatusForm, self).__init__(**kwargs)
if self.instance:
self.initial['slug'] = self.instance.slug
self.initial['status'] = self.instance.status
self.initial['can_skip'] = self.instance.can_skip()
self.initial['is_active'] = self.instance.is_active()
for key, datum in self.instance.get_extra_status_info().iteritems():
self.fields[key] = forms.CharField(required=False)
self.initial[key] = datum
3
Example 28
Project: mezzanine Source File: forms.py
def __init__(self, *args, **kwargs):
super(SettingsForm, self).__init__(*args, **kwargs)
# Create a form field for each editable setting's from its type.
active_language = get_language()
for name in sorted(registry.keys()):
setting = registry[name]
if setting["editable"]:
field_class = FIELD_TYPES.get(setting["type"], forms.CharField)
if settings.USE_MODELTRANSLATION and setting["translatable"]:
for code in OrderedDict(settings.LANGUAGES):
try:
activate(code)
except:
pass
else:
self._init_field(setting, field_class, name, code)
else:
self._init_field(setting, field_class, name)
activate(active_language)
3
Example 29
def __init__(self, *args, **kwargs):
extra = kwargs.pop('extra')
super(PageEditFileContextForm, self).__init__(*args, **kwargs)
for f, c in extra.items():
self.fields['%s' % f] = forms.CharField(initial=c)
3
Example 30
def __init__(self, config=None):
super(self.__class__, self).__init__(config)
self.config = config
if self.config:
keys = [c for c in self.config if c.startswith("choice_") and self.config[c]]
keys = sorted(keys, key=lambda choice: (int) (re.findall(r'\d+', choice)[0]))
else:
keys = []
for k in keys:
self.fields[k] = forms.CharField(required=False, label="Choice")
3
Example 31
def __init__(self, user, initial_device, **kwargs):
"""
`initial_device` is either the user's default device, or the backup
device when the user chooses to enter a backup token. The token will
be verified against all devices, it is not limited to the given
device.
"""
super(AuthenticationTokenForm, self).__init__(**kwargs)
self.user = user
# YubiKey generates a OTP of 44 characters (not digits). So if the
# user's primary device is a YubiKey, replace the otp_token
# IntegerField with a CharField.
if RemoteYubikeyDevice and YubikeyDevice and \
isinstance(initial_device, (RemoteYubikeyDevice, YubikeyDevice)):
self.fields['otp_token'] = forms.CharField(label=_('YubiKey'))
3
Example 32
def __init__(self, *args, **kwargs):
super(TabBlockForm, self).__init__(*args, **kwargs)
instance = kwargs['instance']
if instance:
for tab in instance.tabs.all():
field_name = "tab_title_%d" % tab.id
self.fields[field_name] = forms.CharField()
self.fields[field_name].initial = tab.title
self.fields[field_name].label = _("Tab title")
3
Example 33
Project: django-mysql Source File: test_forms.py
def test_validators_fail_base_max_length(self):
field = SimpleListField(forms.CharField(max_length=5))
with pytest.raises(exceptions.ValidationError) as excinfo:
field.clean('longer,yes')
assert (
excinfo.value.messages[0] ==
'Item 1 in the list did not validate: '
'Ensure this value has at most 5 characters (it has 6).'
)
3
Example 34
def __init__(self, *args, **kwargs):
"""
Saves the identify (phone number) and text field names on self, calls
super(), and then adds the required fields.
"""
# defaults to "text" and "identity"
self.text_name = kwargs.pop('text_name', 'text')
self.identity_name = kwargs.pop('identity_name', 'identity')
super(GenericHttpForm, self).__init__(*args, **kwargs)
self.fields[self.text_name] = forms.CharField()
self.fields[self.identity_name] = forms.CharField()
3
Example 35
Project: django-mysql Source File: test_forms.py
def test_prepare_value(self):
field = SimpleListField(forms.CharField())
value = field.prepare_value(['a', 'b', 'c'])
assert value.split(',') == ['a', 'b', 'c']
assert field.prepare_value('1,a') == '1,a'
3
Example 36
Project: django-modelcluster Source File: test_cluster_form.py
def test_formfield_callback(self):
def formfield_for_dbfield(db_field, **kwargs):
# a particularly stupid formfield_callback that just uses Textarea for everything
return CharField(widget=Textarea, **kwargs)
class BandFormWithFFC(ClusterForm):
formfield_callback = formfield_for_dbfield
class Meta:
model = Band
fields = ['name']
form = BandFormWithFFC()
self.assertEqual(Textarea, type(form['name'].field.widget))
self.assertEqual(Textarea, type(form.formsets['members'].forms[0]['name'].field.widget))
3
Example 37
Project: django-mysql Source File: test_setcharfield.py
def test_model_field_formfield(self):
model_field = SetCharField(models.CharField(max_length=27))
form_field = model_field.formfield()
assert isinstance(form_field, SimpleSetField)
assert isinstance(form_field.base_field, forms.CharField)
assert form_field.base_field.max_length == 27
3
Example 38
def __init__(self, config=None):
super(self.__class__, self).__init__(config)
self.config = config
if self.config:
keys = [c for c in self.config if c.startswith("choice_") and self.config[c]]
keys = sorted(keys, key=lambda choice: (int) (re.findall(r'\d+', choice)[0]))
else:
keys = []
for k in keys:
self.fields[k] = forms.CharField(required=False, label="Choice")
3
Example 39
def get_formfield(self, label, required, choices=None):
field_cls = forms.CharField
kwargs = {'label': label, 'required': required}
if choices is not None:
kwargs['choices'] = choices
kwargs['coerce'] = self.parse
kwargs['empty_value'] = self.get_empty_value()
field_cls = forms.TypedChoiceField
return field_cls, [], kwargs
3
Example 40
def __init__(self, required=True, help_text=None, max_length=None, min_length=None, **kwargs):
# CharField's 'label' and 'initial' parameters are not exposed, as Block handles that functionality natively
# (via 'label' and 'default')
self.field = forms.CharField(
required=required,
help_text=help_text,
max_length=max_length,
min_length=min_length
)
super(CharBlock, self).__init__(**kwargs)
3
Example 41
Project: votainteligente-portal-electoral Source File: template_tags_tests.py
def test_variable_is_field(self):
template = Template("{% load votainteligente_extras %}{% if field|is_field %}si{% else %}no{% endif %}")
field = forms.CharField(required=False, label='Busca tu comuna')
self.assertEqual(template.render(Context({'field': field})), 'si')
data = {'username': 'fierita',
'password1': 'feroz',
'password2': 'feroz',
'email': '[email protected]'}
form = RegistrationForm(data=data)
field = form.fields['username']
self.assertEqual(template.render(Context({'field': field})), 'si')
self.assertEqual(template.render(Context({'field': 'esto es un string'})), 'no')
3
Example 42
Project: pretix Source File: i18n.py
def __init__(self, *args, **kwargs):
fields = []
defaults = {
'widget': self.widget,
'max_length': kwargs.pop('max_length', None),
}
self.langcodes = kwargs.pop('langcodes', [l[0] for l in settings.LANGUAGES])
self.one_required = kwargs.get('required', True)
kwargs['required'] = False
kwargs['widget'] = kwargs['widget'](
langcodes=self.langcodes, field=self, **kwargs.pop('widget_kwargs', {})
)
defaults.update(**kwargs)
for lngcode in self.langcodes:
defaults['label'] = '%s (%s)' % (defaults.get('label'), lngcode)
fields.append(forms.CharField(**defaults))
super().__init__(
fields=fields, require_all_fields=False, *args, **kwargs
)
3
Example 43
Project: hue Source File: forms.py
def __init__(self, table_obj, *args, **kwargs):
"""
@param table_obj is a hive_metastore.thrift Table object,
used to add fields corresponding to partition keys.
"""
super(LoadDataForm, self).__init__(*args, **kwargs)
self.partition_columns = dict()
for i, column in enumerate(table_obj.partition_keys):
# We give these numeric names because column names
# may be unpleasantly arbitrary.
name = "partition_%d" % i
char_field = forms.CharField(required=True, label=_t("%(column_name)s (partition key with type %(column_type)s)") % {'column_name': column.name, 'column_type': column.type})
self.fields[name] = char_field
self.partition_columns[name] = column.name
3
Example 44
Project: elasticstack Source File: test_forms.py
def test_named_search_field(self):
"""Ensure that the `q` field can be optionally used"""
class MyForm(SearchForm):
s = forms.CharField(label='Search')
f = forms.CharField(label='More search')
search_field_name = 's'
form = MyForm()
self.assertTrue('s' in form.fields)
self.assertFalse('q' in form.fields)
3
Example 45
def get_field(self, **kwargs):
"""
Get a Django form field for this type.
The kwargs are passed directly to the field
constructor.
:param kwargs: Kwargs for field constructor
:type kwargs: dict
:return: Form field
:rtype: django.forms.Field
"""
return forms.CharField(**kwargs)
3
Example 46
def build_content_override_field(self):
kwargs = {
"label": "Content",
"required": False,
"initial": self.slot.content_override,
}
return forms.CharField(**kwargs)
3
Example 47
Project: pycon Source File: forms.py
def build_content_override_field(self):
kwargs = {
"label": "Content",
"widget": MarkEdit(),
"required": False,
"initial": self.slot.content_override,
}
return forms.CharField(**kwargs)
3
Example 48
def make_entry_field(self, fieldsubmission=None):
from onlineforms.forms import DividerFieldWidget
return forms.CharField(required=False,
widget=DividerFieldWidget(),
label='',
help_text='')
3
Example 49
Project: django-paypal Source File: forms.py
def __init__(self, button_type="buy", *args, **kwargs):
super(PayPalPaymentsForm, self).__init__(*args, **kwargs)
self.button_type = button_type
if 'initial' in kwargs:
kwargs['initial'] = self._fix_deprecated_paypal_receiver_email(kwargs['initial'])
# Dynamically create, so we can support everything PayPal does.
for k, v in kwargs['initial'].items():
if k not in self.base_fields:
self.fields[k] = forms.CharField(label=k, widget=ValueHiddenInput(), initial=v)
3
Example 50
Project: zorna Source File: forms.py
def __init__(self, *args, **kwargs):
request = kwargs.pop('request')
ckeditor_config_name = SiteOptions.objects.get_ckeditor_config(request)
super(FormsFormPanelForm, self).__init__(*args, **kwargs)
self.fields['panel_header'] = forms.CharField(label=_(u'body'), required=False,
widget=CKEditorWidget(config_name=ckeditor_config_name))
self.fields['panel_footer'] = forms.CharField(label=_(u'body'), required=False,
widget=CKEditorWidget(config_name=ckeditor_config_name))