Python django.forms.fields.CharField() Examples

The following are 22 code examples of django.forms.fields.CharField(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.forms.fields , or try the search function .
Example #1
Source File: forms.py    From callisto-core with GNU Affero General Public License v3.0 7 votes vote down vote up
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 
Example #2
Source File: __init__.py    From django-neomodel with MIT License 6 votes vote down vote up
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 
Example #3
Source File: other.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def make_entry_field(self, fieldsubmission=None):
        from onlineforms.forms import DividerFieldWidget

        return forms.CharField(required=False,
            widget=DividerFieldWidget(),
            label='',
            help_text='') 
Example #4
Source File: test_forms.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
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)) 
Example #5
Source File: test_forms.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_username_field_label(self):

        class CustomAuthenticationForm(AuthenticationForm):
            username = CharField(label="Name", max_length=75)

        form = CustomAuthenticationForm()
        self.assertEqual(form['username'].label, "Name") 
Example #6
Source File: test_forms.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_username_field_label_empty_string(self):

        class CustomAuthenticationForm(AuthenticationForm):
            username = CharField(label='')

        form = CustomAuthenticationForm()
        self.assertEqual(form.fields['username'].label, "") 
Example #7
Source File: test_forms.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
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)) 
Example #8
Source File: test_forms.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_username_field_label(self):

        class CustomAuthenticationForm(AuthenticationForm):
            username = CharField(label="Name", max_length=75)

        form = CustomAuthenticationForm()
        self.assertEqual(form['username'].label, "Name") 
Example #9
Source File: forms.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["new_password1"] = CharField(
            max_length=settings.PASSWORD_MAX_LENGTH,
            min_length=settings.PASSWORD_MIN_LENGTH,
            label=self.password1_label,
            widget=PasswordInput(),
            error_messages={"required": REQUIRED_ERROR.format("password")},
        ) 
Example #10
Source File: forms.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if TenantApi.site_settings("DISABLE_SIGNUP", cast=bool, request=self.request):
            label = "Email Address"
        else:
            label = "Username"
        self.fields["username"] = CharField(
            max_length=64,
            label=label,
            error_messages={"required": REQUIRED_ERROR.format(label)},
        ) 
Example #11
Source File: test_fields.py    From django-better-admin-arrayfield with MIT License 5 votes vote down vote up
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) 
Example #12
Source File: test_fields.py    From django-better-admin-arrayfield with MIT License 5 votes vote down vote up
def test_field_not_required():
    field = DynamicArrayField(CharField(max_length=10), required=False)
    data = []
    field.clean(data)
    data = ["12", "13"]
    field.clean(data) 
Example #13
Source File: other.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #14
Source File: testcases.py    From luscan-devel with GNU General Public License v2.0 4 votes vote down vote up
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 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.assertTrue(isinstance(fieldclass(*field_args, **field_kwargs),
                                       fieldclass)) 
Example #15
Source File: testcases.py    From openhgsenti with Apache License 2.0 4 votes vote down vote up
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) 
Example #16
Source File: testcases.py    From python2017 with MIT License 4 votes vote down vote up
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) 
Example #17
Source File: testcases.py    From python with Apache License 2.0 4 votes vote down vote up
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) 
Example #18
Source File: testcases.py    From Hands-On-Application-Development-with-PyCharm with MIT License 4 votes vote down vote up
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) 
Example #19
Source File: test_django_cassandra_models.py    From django-cassandra-engine with BSD 2-Clause "Simplified" License 4 votes vote down vote up
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)) 
Example #20
Source File: views.py    From panhandler with Apache License 2.0 4 votes vote down vote up
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 
Example #21
Source File: testcases.py    From bioforum with MIT License 4 votes vote down vote up
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) 
Example #22
Source File: testcases.py    From GTDWeb with GNU General Public License v2.0 4 votes vote down vote up
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)