本文整理汇总了Python中django.forms.fields.CharField方法的典型用法代码示例。如果您正苦于以下问题:Python fields.CharField方法的具体用法?Python fields.CharField怎么用?Python fields.CharField使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.forms.fields
的用法示例。
在下文中一共展示了fields.CharField方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from django.forms import fields [as 别名]
# 或者: from django.forms.fields import CharField [as 别名]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["new_password1"] = CharField(
min_length=settings.PASSWORD_MIN_LENGTH,
max_length=settings.PASSWORD_MAX_LENGTH,
label="Enter your new password",
widget=PasswordInput(attrs={"autocomplete": "off"}),
error_messages={"required": REQUIRED_ERROR.format("password")},
)
self.fields["new_password2"].label = "Confirm new password"
self.fields["new_password2"].widget.attrs["autocomplete"] = "off"
self.fields["old_password"].label = "Old password"
self.fields["old_password"].widget.attrs["autocomplete"] = "off"
# in original PasswordChangeForm file to reorder fields
示例2: __init__
# 需要导入模块: from django.forms import fields [as 别名]
# 或者: from django.forms.fields import CharField [as 别名]
def __init__(self, prop, name):
self.prop = prop
self.name = name
self.help_text = getattr(prop, 'help_text', '')
self.primary_key = getattr(prop, 'primary_key', False)
self.label = prop.label if prop.label else name
form_cls = getattr(prop, 'form_field_class', 'Field') # get field string
self.form_class = getattr(fields, form_cls, fields.CharField)
self._has_default = prop.has_default
self.required = prop.required
self.blank = not self.required
self.choices = getattr(prop, 'choices', None)
self.creation_counter = DjangoField.creation_counter
DjangoField.creation_counter += 1
示例3: __init__
# 需要导入模块: from django.forms import fields [as 别名]
# 或者: from django.forms.fields import CharField [as 别名]
def __init__(self, max=20, min=2, other_required=False, *args, **kwargs):
self.min = int(min)
self.max = int(max)
self.required = other_required
kwargs['widget'] = CustomMultipleInputWidget(max=max, min=min)
self.field_set = [fields.CharField() for _ in range(int(max))]
super(CustomMultipleInputField, self).__init__(fields=self.field_set, *args, **kwargs)
示例4: make_entry_field
# 需要导入模块: from django.forms import fields [as 别名]
# 或者: from django.forms.fields import CharField [as 别名]
def make_entry_field(self, fieldsubmission=None):
from onlineforms.forms import DividerFieldWidget
return forms.CharField(required=False,
widget=DividerFieldWidget(),
label='',
help_text='')
示例5: test_field_not_required
# 需要导入模块: from django.forms import fields [as 别名]
# 或者: from django.forms.fields import CharField [as 别名]
def test_field_not_required():
field = DynamicArrayField(CharField(max_length=10), required=False)
data = []
field.clean(data)
data = ["12", "13"]
field.clean(data)
示例6: test_field_required
# 需要导入模块: from django.forms import fields [as 别名]
# 或者: from django.forms.fields import CharField [as 别名]
def test_field_required():
field = DynamicArrayField(CharField(max_length=10), required=True)
data = []
with pytest.raises(ValidationError):
field.clean(data)
data = ["12", "13"]
field.clean(data)
示例7: test_username_field_label
# 需要导入模块: from django.forms import fields [as 别名]
# 或者: from django.forms.fields import CharField [as 别名]
def test_username_field_label(self):
class CustomAuthenticationForm(AuthenticationForm):
username = CharField(label="Name", max_length=75)
form = CustomAuthenticationForm()
self.assertEqual(form['username'].label, "Name")
示例8: test_username_field_label_not_set
# 需要导入模块: from django.forms import fields [as 别名]
# 或者: from django.forms.fields import CharField [as 别名]
def test_username_field_label_not_set(self):
class CustomAuthenticationForm(AuthenticationForm):
username = CharField()
form = CustomAuthenticationForm()
username_field = User._meta.get_field(User.USERNAME_FIELD)
self.assertEqual(form.fields['username'].label, capfirst(username_field.verbose_name))
示例9: test_username_field_label_empty_string
# 需要导入模块: from django.forms import fields [as 别名]
# 或者: from django.forms.fields import CharField [as 别名]
def test_username_field_label_empty_string(self):
class CustomAuthenticationForm(AuthenticationForm):
username = CharField(label='')
form = CustomAuthenticationForm()
self.assertEqual(form.fields['username'].label, "")
示例10: assertFieldOutput
# 需要导入模块: from django.forms import fields [as 别名]
# 或者: from django.forms.fields import CharField [as 别名]
def assertFieldOutput(self, fieldclass, valid, invalid, field_args=None,
field_kwargs=None, empty_value=''):
"""
Asserts that a form field behaves correctly with various inputs.
Args:
fieldclass: the class of the field to be tested.
valid: a dictionary mapping valid inputs to their expected
cleaned values.
invalid: a dictionary mapping invalid inputs to one or more
raised error messages.
field_args: the args passed to instantiate the field
field_kwargs: the kwargs passed to instantiate the field
empty_value: the expected clean output for inputs in empty_values
"""
if field_args is None:
field_args = []
if field_kwargs is None:
field_kwargs = {}
required = fieldclass(*field_args, **field_kwargs)
optional = fieldclass(*field_args,
**dict(field_kwargs, required=False))
# test valid inputs
for input, output in valid.items():
self.assertEqual(required.clean(input), output)
self.assertEqual(optional.clean(input), output)
# test invalid inputs
for input, errors in invalid.items():
with self.assertRaises(ValidationError) as context_manager:
required.clean(input)
self.assertEqual(context_manager.exception.messages, errors)
with self.assertRaises(ValidationError) as context_manager:
optional.clean(input)
self.assertEqual(context_manager.exception.messages, errors)
# test required inputs
error_required = [force_text(required.error_messages['required'])]
for e in required.empty_values:
with self.assertRaises(ValidationError) as context_manager:
required.clean(e)
self.assertEqual(context_manager.exception.messages,
error_required)
self.assertEqual(optional.clean(e), empty_value)
# test that max_length and min_length are always accepted
if issubclass(fieldclass, CharField):
field_kwargs.update({'min_length': 2, 'max_length': 20})
self.assertIsInstance(fieldclass(*field_args, **field_kwargs),
fieldclass)
示例11: assertFieldOutput
# 需要导入模块: from django.forms import fields [as 别名]
# 或者: from django.forms.fields import CharField [as 别名]
def assertFieldOutput(self, fieldclass, valid, invalid, field_args=None,
field_kwargs=None, empty_value=''):
"""
Assert that a form field behaves correctly with various inputs.
Args:
fieldclass: the class of the field to be tested.
valid: a dictionary mapping valid inputs to their expected
cleaned values.
invalid: a dictionary mapping invalid inputs to one or more
raised error messages.
field_args: the args passed to instantiate the field
field_kwargs: the kwargs passed to instantiate the field
empty_value: the expected clean output for inputs in empty_values
"""
if field_args is None:
field_args = []
if field_kwargs is None:
field_kwargs = {}
required = fieldclass(*field_args, **field_kwargs)
optional = fieldclass(*field_args, **dict(field_kwargs, required=False))
# test valid inputs
for input, output in valid.items():
self.assertEqual(required.clean(input), output)
self.assertEqual(optional.clean(input), output)
# test invalid inputs
for input, errors in invalid.items():
with self.assertRaises(ValidationError) as context_manager:
required.clean(input)
self.assertEqual(context_manager.exception.messages, errors)
with self.assertRaises(ValidationError) as context_manager:
optional.clean(input)
self.assertEqual(context_manager.exception.messages, errors)
# test required inputs
error_required = [force_text(required.error_messages['required'])]
for e in required.empty_values:
with self.assertRaises(ValidationError) as context_manager:
required.clean(e)
self.assertEqual(context_manager.exception.messages, error_required)
self.assertEqual(optional.clean(e), empty_value)
# test that max_length and min_length are always accepted
if issubclass(fieldclass, CharField):
field_kwargs.update({'min_length': 2, 'max_length': 20})
self.assertIsInstance(fieldclass(*field_args, **field_kwargs), fieldclass)
示例12: generate_dynamic_form
# 需要导入模块: from django.forms import fields [as 别名]
# 或者: from django.forms.fields import CharField [as 别名]
def generate_dynamic_form(self, data=None) -> Form:
form = Form(data=data)
meta = self.meta
if meta is None:
raise SnippetRequiredException('Could not find a valid skillet!!')
mode = self.get_value_from_workflow('mode', 'online')
if mode == 'online':
self.title = 'PAN-OS NGFW to Validate'
self.help_text = 'This form allows you to enter the connection information for a PAN-OS NGFW. This' \
'tool will connect to that device and pull it\'s configuration to perform the' \
'validation.'
target_ip_label = 'Target IP'
target_username_label = 'Target Username'
target_password_label = 'Target Password'
target_ip = self.get_value_from_workflow('TARGET_IP', '')
# target_port = self.get_value_from_workflow('TARGET_PORT', 443)
target_username = self.get_value_from_workflow('TARGET_USERNAME', '')
target_password = self.get_value_from_workflow('TARGET_PASSWORD', '')
target_ip_field = fields.CharField(label=target_ip_label, initial=target_ip, required=True,
validators=[FqdnOrIp])
target_username_field = fields.CharField(label=target_username_label, initial=target_username, required=True)
target_password_field = fields.CharField(widget=widgets.PasswordInput(render_value=True), required=True,
label=target_password_label,
initial=target_password)
form.fields['TARGET_IP'] = target_ip_field
form.fields['TARGET_USERNAME'] = target_username_field
form.fields['TARGET_PASSWORD'] = target_password_field
else:
self.title = 'PAN-OS XML Configuration to Validate'
self.help_text = 'This form allows you to paste in a full configuration from a PAN-OS NGFW. This ' \
'will then be used to perform the validation.'
label = 'Configuration'
initial = self.get_value_from_workflow('config', '<xml></xml>')
help_text = 'Paste the full XML configuration file to validate here.'
config_field = fields.CharField(label=label, initial=initial, required=True,
help_text=help_text,
widget=widgets.Textarea(attrs={'cols': 40}))
form.fields['config'] = config_field
return form
示例13: test_methods
# 需要导入模块: from django.forms import fields [as 别名]
# 或者: from django.forms.fields import CharField [as 别名]
def test_methods(self):
model_fields = self.family_member._meta._get_fields()
for field in model_fields:
self.assertEqual(field.get_attname(), field.attname)
self.assertEqual(
field.get_cache_name(), '_{}_cache'.format(field.name)
)
self.assertEqual(
field.value_to_string(self.family_member),
str(getattr(self.family_member, field.name)),
)
self.assertEqual(
field.pre_save(self.family_member, True),
getattr(self.family_member, field.name),
)
self.assertEqual(
field.get_prep_value(self.family_member.id), self.some_uuid
)
self.assertEqual(
field.get_db_prep_save(self.family_member.id, connection=None),
self.some_uuid,
)
self.assertTrue(isinstance(field.formfield(), fields.CharField))
self.assertEqual(
field.get_internal_type(), field.__class__.__name__
)
self.assertEqual(
field.get_attname_column(),
(field.db_field_name, field.db_field_name),
)
self.assertEqual(field.get_db_converters(), [])
field_with_default = self.family_member._meta.get_field('id')
self.assertTrue(
isinstance(
field_with_default.get_default(), type(self.family_member.id)
)
)
# in Django, 'has_default' is a function, while in python-driver
# it is a property unfortunately.
self.assertEqual(field_with_default.has_default, True)
text_field = self.family_member._meta.get_field('last_name')
text_field.save_form_data(instance=self.family_member, data='new data')
self.assertEqual(self.family_member.last_name, 'new data')
self.assertIsNone(field.run_validators(text_field.value))
示例14: assertFieldOutput
# 需要导入模块: from django.forms import fields [as 别名]
# 或者: from django.forms.fields import CharField [as 别名]
def assertFieldOutput(self, fieldclass, valid, invalid, field_args=None,
field_kwargs=None, empty_value=''):
"""
Assert that a form field behaves correctly with various inputs.
Args:
fieldclass: the class of the field to be tested.
valid: a dictionary mapping valid inputs to their expected
cleaned values.
invalid: a dictionary mapping invalid inputs to one or more
raised error messages.
field_args: the args passed to instantiate the field
field_kwargs: the kwargs passed to instantiate the field
empty_value: the expected clean output for inputs in empty_values
"""
if field_args is None:
field_args = []
if field_kwargs is None:
field_kwargs = {}
required = fieldclass(*field_args, **field_kwargs)
optional = fieldclass(*field_args, **{**field_kwargs, 'required': False})
# test valid inputs
for input, output in valid.items():
self.assertEqual(required.clean(input), output)
self.assertEqual(optional.clean(input), output)
# test invalid inputs
for input, errors in invalid.items():
with self.assertRaises(ValidationError) as context_manager:
required.clean(input)
self.assertEqual(context_manager.exception.messages, errors)
with self.assertRaises(ValidationError) as context_manager:
optional.clean(input)
self.assertEqual(context_manager.exception.messages, errors)
# test required inputs
error_required = [required.error_messages['required']]
for e in required.empty_values:
with self.assertRaises(ValidationError) as context_manager:
required.clean(e)
self.assertEqual(context_manager.exception.messages, error_required)
self.assertEqual(optional.clean(e), empty_value)
# test that max_length and min_length are always accepted
if issubclass(fieldclass, CharField):
field_kwargs.update({'min_length': 2, 'max_length': 20})
self.assertIsInstance(fieldclass(*field_args, **field_kwargs), fieldclass)
示例15: assertFieldOutput
# 需要导入模块: from django.forms import fields [as 别名]
# 或者: from django.forms.fields import CharField [as 别名]
def assertFieldOutput(self, fieldclass, valid, invalid, field_args=None,
field_kwargs=None, empty_value=''):
"""
Asserts that a form field behaves correctly with various inputs.
Args:
fieldclass: the class of the field to be tested.
valid: a dictionary mapping valid inputs to their expected
cleaned values.
invalid: a dictionary mapping invalid inputs to one or more
raised error messages.
field_args: the args passed to instantiate the field
field_kwargs: the kwargs passed to instantiate the field
empty_value: the expected clean output for inputs in empty_values
"""
if field_args is None:
field_args = []
if field_kwargs is None:
field_kwargs = {}
required = fieldclass(*field_args, **field_kwargs)
optional = fieldclass(*field_args, **dict(field_kwargs, required=False))
# test valid inputs
for input, output in valid.items():
self.assertEqual(required.clean(input), output)
self.assertEqual(optional.clean(input), output)
# test invalid inputs
for input, errors in invalid.items():
with self.assertRaises(ValidationError) as context_manager:
required.clean(input)
self.assertEqual(context_manager.exception.messages, errors)
with self.assertRaises(ValidationError) as context_manager:
optional.clean(input)
self.assertEqual(context_manager.exception.messages, errors)
# test required inputs
error_required = [force_text(required.error_messages['required'])]
for e in required.empty_values:
with self.assertRaises(ValidationError) as context_manager:
required.clean(e)
self.assertEqual(context_manager.exception.messages, error_required)
self.assertEqual(optional.clean(e), empty_value)
# test that max_length and min_length are always accepted
if issubclass(fieldclass, CharField):
field_kwargs.update({'min_length': 2, 'max_length': 20})
self.assertIsInstance(fieldclass(*field_args, **field_kwargs), fieldclass)