我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.forms.TextInput()。
def __init__(self, *args, **kwargs): questions = sorted(list(kwargs.pop('questions')), key=attrgetter("number")) super(SurveyForm, self).__init__(*args, **kwargs) for i, question in enumerate(questions): if question.type == 'MC': vrs = question.variants self.fields['question_%s' % question.id] = forms.ChoiceField( label=question.text, choices=[(j, vrs[j]) for j in range(len(vrs))], widget=forms.RadioSelect, required=True) elif question.type == 'NR': self.fields['question_%s' % question.id] = forms.ChoiceField( choices=[(i, i) for i in range(1, 11)], label=question.text) elif question.type == 'TE': self.fields['question_%s' % question.id] = forms.CharField( max_length=512, required=True, widget=forms.TextInput(), label=question.text)
def render(self, name, value, attrs=None): if not attrs.has_key('class'): attrs['class'] = name attrs_text = attrs.copy() attrs_pass = attrs.copy() # render name only for visible element name_pass, name_text = name, '' # disable autocomplete for text attrs_text['autocomplete'] = 'off' # set either text or password fields to hidden temp_attrs = attrs_text if not self.attrs.has_key('default') or self.attrs['default'] == TogglePasswordInput.TEXT: temp_attrs = attrs_pass name_text, name_pass = name_pass, name_text # remove id so we don't get two field with same ids del temp_attrs['id'] temp_attrs['style'] = 'display:none;' output = forms.TextInput().render(name_text, value, attrs_text) output += forms.PasswordInput.render(self, name_pass, value, attrs_pass) output += '<a title="'+_('show/hide password')+'" data-target-class="'+attrs['class']+'" class="toggle-password" href="#"></a>' return mark_safe(output)
def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) # Add honeypots self.honeypot_fieldnames = "address", "phone" self.honeypot_class = ''.join( random.choice(string.ascii_uppercase + string.digits) for __ in range(10)) self.honeypot_jsfunction = 'f' + ''.join( random.choice(string.ascii_uppercase + string.digits) for __ in range(10)) for fieldname in self.honeypot_fieldnames: self.fields[fieldname] = forms.CharField( widget=forms.TextInput(attrs={'class': self.honeypot_class}), required=False, )
def __init__(self, choices, validators, *args, **kwargs): """ :param validators: A dict that maps query type values to validators. """ if validators is None: validators = {} super(MultitypeQueryField, self).__init__(*args, **kwargs) self.fields = ( forms.ChoiceField(choices=choices), forms.CharField(min_length=1) ) self.widget = MultitypeQueryWidget( (forms.Select(choices=choices), forms.TextInput()) ) self.query_validators = validators
def setUp(self): super(OmniModelFormTestCase, self).setUp() self.omniform = OmniModelFormFactory.create() self.field_1 = OmniCharField( name='title', label='Please give us a title', required=True, widget_class='django.forms.widgets.TextInput', order=0, initial='Some title...', form=self.omniform ) self.field_1.save() self.field_2 = OmniBooleanField( name='agree', label='Please agree', required=True, widget_class='django.forms.widgets.CheckboxInput', order=1, initial=True, form=self.omniform ) self.field_2.save() self.handler_1 = OmniFormEmailHandlerFactory.create(form=self.omniform) self.handler_2 = OmniFormEmailHandlerFactory.create(form=self.omniform)
def test_get_field(self): """ The _get_field method should return a form field instance """ field_1 = self.omniform._get_field('title') field_2 = self.omniform._get_field('agree') field_3 = self.omniform._get_field('fictional') self.assertIsInstance(field_1, forms.CharField) self.assertIsInstance(field_1.widget, forms.TextInput) self.assertEqual(field_1.label, 'Please give us a title') self.assertTrue(field_1.required) self.assertIsInstance(field_2, forms.BooleanField) self.assertIsInstance(field_2.widget, forms.CheckboxInput) self.assertEqual(field_2.label, 'Please agree') self.assertTrue(field_2.required) self.assertIsNone(field_3)
def test_as_form_field(self): """ The as_form_field method should pass the min_length and max_length to the field constructor """ form = OmniModelFormFactory.create() field = OmniCharField( name='title', label='Please give us a title', required=True, widget_class='django.forms.widgets.TextInput', order=0, initial='Some title...', min_length=10, max_length=150, form=form ) field.save() field_instance = field.as_form_field() self.assertEqual(field_instance.min_length, 10) self.assertEqual(field_instance.max_length, 150)
def test_as_form_field(self): """ The as_form_field method should pass protocol and unpack_ipv4 to the field constructor """ form = OmniModelFormFactory.create() field = OmniDecimalField( name='title', label='Please give us a title', required=True, widget_class='django.forms.widgets.TextInput', order=0, initial=10.8, min_value=0.0, max_value=999.987, max_digits=999, decimal_places=3, form=form ) field.save() field_instance = field.as_form_field() self.assertEqual(field_instance.min_value, 0.0) self.assertEqual(field_instance.max_value, 999.987) self.assertEqual(field_instance.max_digits, 999) self.assertEqual(field_instance.decimal_places, 3)
def test_as_form_field(self): """ The as_form_field method should pass protocol and unpack_ipv4 to the field constructor """ form = OmniModelFormFactory.create() field = OmniGenericIPAddressField( name='title', label='Please give us a title', required=True, widget_class='django.forms.widgets.TextInput', order=0, initial='192.168.1.1', protocol=OmniGenericIPAddressField.PROTOCOL_BOTH, unpack_ipv4=True, form=form ) field.save() field_instance = field.as_form_field() self.assertEqual(field_instance.validators[0].__name__, 'validate_ipv46_address') self.assertTrue(field_instance.unpack_ipv4)
def test_unpack_ipv4_raises_validation_error_with_ipv4(self): """ The clean method should raise a validation error if unpack_ipv4 is selected with any protocol other than both """ form = OmniModelFormFactory.create() field = OmniGenericIPAddressField( name='title', label='Please give us a title', required=True, widget_class='django.forms.widgets.TextInput', order=0, initial='192.168.1.1', protocol=OmniGenericIPAddressField.PROTOCOL_IPV4, unpack_ipv4=True, form=form ) self.assertRaises(ValidationError, field.full_clean)
def test_unpack_ipv4_cleans_without_error(self): """ The clean method should not raise a validation error if unpack_ipv4 is selected with protocol both """ form = OmniModelFormFactory.create() field = OmniGenericIPAddressField( name='title', label='Please give us a title', required=True, widget_class='django.forms.widgets.TextInput', order=0, initial='192.168.1.1', protocol=OmniGenericIPAddressField.PROTOCOL_BOTH, unpack_ipv4=True, form=form ) field.save() field.full_clean()
def test_as_form_field(self): """ The as_form_field method should pass the min_length and max_length to the field constructor """ form = OmniModelFormFactory.create() field = OmniUrlField( name='title', label='Please give us a title', required=True, widget_class='django.forms.widgets.TextInput', order=0, initial='http://www.google.com', min_length=10, max_length=150, form=form ) field.save() field_instance = field.as_form_field() self.assertEqual(field_instance.min_length, 10) self.assertEqual(field_instance.max_length, 150)
def __init__(self, *args, **kwargs): self._template = kwargs.pop('template', None) self._lookup = OrderedDict() self._created_fields = {} super(WorklistDefaultsForm, self).__init__(*args, **kwargs) # create a field for default values in each column of template for x in self._template.worklistcolumn_set.order_by('ordering', ): form_name = 'col.%s' % (x.pk, ) self.initial[form_name] = x.get_default() self.fields[form_name] = self._created_fields[form_name] = forms.CharField( help_text=x.help_text, initial=x.get_default(), label=str(x), required=False, widget=forms.TextInput(attrs={'size': 30}), ) self._lookup[form_name] = x
def __init__(self, *args, **kwargs): user_id = kwargs.pop('user_id') super().__init__(*args, **kwargs) try: coord_settings = OrganisationAdmin.objects.get(user_id=user_id) except OrganisationAdmin.DoesNotExist: coord_settings = OrganisationAdmin() coord_settings.account_id = 'Not set' coord_settings.secret = 'Not set' self.fields['account_id'] = forms.CharField(widget=forms.TextInput( attrs={'class': 'input-field-coord-account_id', 'value': coord_settings.account_id}) ) self.fields['secret'] = forms.CharField(widget=forms.TextInput( attrs={'class': 'input-field-coord-secret', 'value': coord_settings.secret}) )
def test_constructor_attrs(self): widget = forms.NestedFormWidget( ('A', 'B', 'C'), ((TextInput()), (TextInput()), (TextInput()) ), attrs={'id': 'bar'}, ) self.check_html(widget, 'name', ['john', 'winston', 'lennon'], html="""<ul> <li><label for="bar_a">A:</label><input id="bar_a" name="name_a" type="text" value="john" /></li> <li><label for="bar_b">B:</label><input id="bar_b" name="name_b" type="text" value="winston" /></li> <li><label for="bar_c">C:</label><input id="bar_c" name="name_c" type="text" value="lennon" /></li> </ul> """ )
def test_nested_multiwidget(self): """ NestedFormWidget can be composed of other NestedFormWidgets. """ widget = forms.NestedFormWidget( ('A', 'B'), (TextInput(), forms.NestedFormWidget( ('C', 'D'), (TextInput(), TextInput()) ) ) ) self.check_html(widget, 'name', ['Singer', ['John', 'Lennon']], html=( """ <ul> <li><label>A:</label><input name="name_a" type="text" value="Singer" /></li> <li><label>B:</label><ul> <li><label>C:</label><input name="name_b_c" type="text" value="John" /></li> <li><label>D:</label><input name="name_b_d" type="text" value="Lennon" /></li> </ul> </li> </ul> """ ))
def test_form_local_path_field(self, redirect_form): """Form should have a 'local_path' field""" field = redirect_form.fields['local_path'] assert isinstance(field, forms.CharField) assert isinstance(field.widget, forms.TextInput) assert field.label == 'Fake local path' assert ( field.widget.attrs['placeholder'] == '/2017/04/04/we-are-all-doomed' )
def test_form_destination_url_field(self, redirect_form): """Form should have a 'destination_url' field""" field = redirect_form.fields['destination_url'] assert isinstance(field, forms.CharField) assert isinstance(field.widget, forms.TextInput) assert field.label == 'Destination URL' assert ( field.widget.attrs['placeholder'] == 'https://github.com/pawelad/fakester' )
def nested_formset_factory(parent_model, child_model, grandchild_model): parent_child = inlineformset_factory( parent_model, child_model, formset=BaseNestedFormset, max_num=1, fields="__all__", widgets={'type': forms.RadioSelect(), 'text': forms.Textarea({'class': 'materialize-textarea'}) }, extra=1, exclude=['help_text', 'order', ], can_order=True, can_delete=True, ) parent_child.nested_formset_class = inlineformset_factory( child_model, grandchild_model, max_num=8, extra=4, validate_max=True, widgets={'text': forms.TextInput()}, exclude=['ORDER', ], can_delete=True, ) return parent_child # The best link: http://yergler.net/blog/2009/09/27/nested-formsets-with-django/ # Nested formset
def __init__(self, *args, **kwargs): if kwargs: profession = kwargs.pop("profession") # client is the parameter passed from views.py employment = kwargs.pop("employment") education = kwargs.pop("education") super(ProfileForm, self).__init__(*args, **kwargs) self.fields['profession'] = forms.CharField(widget=forms.TextInput(attrs={'class': 'input', 'value': profession}), required=False) self.fields['employment'] = forms.CharField(widget=forms.TextInput(attrs={'class': 'input', 'value': employment}), required=False) self.fields['education'] = forms.CharField(widget=forms.TextInput(attrs={'class': 'input', 'value': education}), required=False) else: super(ProfileForm, self).__init__(*args, **kwargs)
def render(self, name, value, attrs=None): # Place a percent sign after a smaller text field try: value = str("%.2f" % (Decimal(value) * 100)) except: value = "N/A" attrs['size'] = attrs['max_length'] = 6 return mark_safe(super(forms.TextInput, self).render(name, value, attrs) + '%')
def __init__(self, choices, *args, **kwargs): fields = [ forms.ChoiceField(choices=choices, widget=forms.RadioSelect, required=False), forms.CharField(required=False, widget=forms.TextInput, help_text='Other') ] self.widget = OptionalChoiceWidget(widgets=[f.widget for f in fields]) super().__init__(required=False, fields=fields, *args, **kwargs)
def __init__(self, vpu_help=None, *args, **kwargs): super(EconomicResourceForm, self).__init__(*args, **kwargs) if vpu_help: self.fields["value_per_unit_of_use"].widget=forms.TextInput(attrs={'value': '0.0', 'class': 'quantity'}) self.fields["value_per_unit_of_use"].help_text = vpu_help
def __init__(self, *args, **kwargs): super(PackageForm, self).__init__(*args, **kwargs) self.fields['category'].help_text = package_help_text() self.fields['repo_url'].widget = TextInput(attrs={ 'placeholder': 'ex: https://github.com/steemit/steem' }) self.fields['description'].widget = Textarea(attrs={ "placeholder": "Write few sentences about this projects. What problem does it solve? Who is it for?" }) self.fields['contact_url'].widget = TextInput(attrs={ "placeholder": "Link to channel on steemit.chat, discord, slack, etc" })
def __init__(self, *args, matching_validators, **kwargs): self.matching_validators = matching_validators kwargs.update({ 'label': self.matching_validators.titled(), }) self.widget = forms.TextInput( attrs={'placeholder': self.matching_validators.examples()} ) super().__init__(*args, **kwargs)
def __init__(self, url=None, forward=None, attrs=None, *args, **kwargs): forms.TextInput.__init__(self, *args, **kwargs) WidgetMixin.__init__( self, url=url, forward=forward ) self.attrs.update(attrs)
def render(self, name, value, attrs=None, renderer=None): """ Proxy Django's TextInput.render() """ html = ''' <input id="{id}" {attrs} type="text" name="{name}" value="{value}" /> '''.format( id=attrs['id'], name=name, value=force_text('' if value is None else value), attrs=flatatt(self.build_attrs(attrs)), ) return mark_safe(html)
def __init__(self, attrs=None): widgets = ( forms.TextInput(), forms.TextInput(), ) super(GeopositionWidget, self).__init__(widgets, attrs)
def formfield(self, **kwargs): kwargs['widget'] = TextInput(attrs={'style': 'width: 400px'}) return super(CommaSeparatedEmailField, self).formfield(**kwargs)
def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) if (hasattr(settings, 'USERNAME_IS_EMAIL') and getattr(settings, 'USERNAME_IS_EMAIL')): self.fields.pop('username') self.fields['email'].widget = forms.TextInput( attrs={"autofocus": "autofocus"})
def __init__(self, *args, **kwargs): super(ForgotPasswordForm, self).__init__(*args, **kwargs) if (hasattr(settings, 'USERNAME_IS_EMAIL') and getattr(settings, 'USERNAME_IS_EMAIL')): self.fields.pop('username') self.fields['email'].widget = forms.TextInput( attrs={"autofocus": "autofocus"})
def get_form_field(self, **kwargs): if self.raw: from django import forms defaults = kwargs defaults['widget'] = forms.TextInput(attrs={'size': 80}) else: defaults = FakeModelProperty.get_fake_defaults(self.model, **kwargs) return super(FakeModelProperty, self).get_form_field(**defaults)
def mark_readonly(form): form.readonly = True for field in form.fields.values(): if isinstance(field.widget, (forms.TextInput, forms.Textarea)): field.widget.attrs['readonly'] = 'readonly' field.widget.attrs['placeholder'] = \ '-- {0} --'.format(_('No information given')) else: field.widget.attrs['readonly'] = 'readonly' field.widget.attrs['disabled'] = 'disabled'
def formfield(self, **kwargs): defaults = {'widget': django_forms.TextInput(attrs={'class': 'vIntegerField'}), 'initial': self.default} defaults.update(kwargs) return django_forms.FloatField(**defaults) #-------------------------------------------------------------------------------
def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(LoginForm, self).__init__(*args, **kwargs) if app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.EMAIL: login_widget = forms.TextInput(attrs={'type': 'email', 'placeholder': _('E-mail address'), 'autofocus': 'autofocus'}) login_field = forms.EmailField(label=_("E-mail"), widget=login_widget) elif app_settings.AUTHENTICATION_METHOD \ == AuthenticationMethod.USERNAME: login_widget = forms.TextInput(attrs={'placeholder': _('Username'), 'autofocus': 'autofocus'}) login_field = forms.CharField( label=_("Username"), widget=login_widget, max_length=get_username_max_length()) else: assert app_settings.AUTHENTICATION_METHOD \ == AuthenticationMethod.USERNAME_EMAIL login_widget = forms.TextInput(attrs={'placeholder': _('Username or e-mail'), 'autofocus': 'autofocus'}) login_field = forms.CharField(label=pgettext("field label", "Login"), widget=login_widget) self.fields["login"] = login_field set_form_field_order(self, ["login", "password", "remember"]) if app_settings.SESSION_REMEMBER is not None: del self.fields['remember']
def __init__(self, *args, **kwargs): defaults = {'widget': forms.TextInput} kwargs.update(defaults) super(CronFormField, self).__init__(*args, **kwargs)
def test_widget_additions(self): widget = TextInput() attrs = self.field.widget_attrs(widget) self.assertIn('person_number', attrs['class']) self.assertEqual(attrs['placeholder'], 'YYYYMMDD-XXXX')
def __init__(self, *args, **kwargs): super(CMSToolbarLoginForm, self).__init__(*args, **kwargs) kwargs['prefix'] = kwargs.get('prefix', 'cms') self.fields['username'].widget = forms.TextInput( attrs = { 'required': 'required' }) self.fields['password'].widget = forms.PasswordInput( attrs = { 'required': 'required' })
def __init__(self, *args, **kwargs): backend = kwargs.pop('backend', None) database = kwargs.pop('database', None) collection = kwargs.pop('collection', None) super(CollectionQueryForm, self).__init__(*args, **kwargs) if backend and database and collection: # TODO(LH): provide contingency if no Distillery is associated with # the warehouse distillery = Distillery.objects.get_by_natural_key(backend, database, collection) field_choices = self._get_field_choices(distillery.bottle) operator_choices = self._get_operator_choices() self.fields['datafield'] = forms.ChoiceField( choices=field_choices, label='Field name', widget=forms.Select( attrs={'class': 'field'}, ) ) self.fields['operator'] = forms.ChoiceField( choices=operator_choices, widget=forms.Select( attrs={'class': 'operator'}, ) ) self.fields['value'] = forms.CharField( required=False, widget=forms.TextInput( attrs={'class': 'value'}, ) )
def __init__(self, *args, **kwargs): super(PlaceholderInsteadOfLabelMixin, self).__init__(*args, **kwargs) for field_name in self.fields: field = self.fields.get(field_name) if field: if type(field.widget) in (forms.TextInput, forms.DateInput): field.widget = forms.TextInput(attrs={'placeholder': field.label}) field.label = None
def formfield(self, **kwargs): defaults = { 'widget': forms.TextInput, } defaults.update(kwargs) return super(VarcharField, self).formfield(**defaults)
def __init__(self, choices, validators={}, *args, **kwargs): """ :param validators: A dict that maps query type values to validators. """ super(MultitypeQueryField, self).__init__(*args, **kwargs) self.fields = ( forms.CharField(min_length=1), forms.ChoiceField(choices=choices) ) self.widget = MultitypeQueryWidget( (forms.TextInput(), forms.Select(choices=choices)) ) self.query_validators = validators
def __init__(self, *args, **kwargs): super(ServiceChoiceForm, self).__init__(*args, **kwargs) # NB: Setting the TextInput to hidden is done to display the label. # The HiddenInput widget will remove the label self.fields['netbox'] = forms.CharField( label='IP Device', widget=forms.TextInput(attrs={'type': 'hidden'}) ) self.fields['service'] = forms.ChoiceField( choices=sorted(self._build_checker_choices()), widget=forms.Select(attrs={'class': 'select2'}) ) self.helper = FormHelper(self) self.helper.form_tag = False
def setUp(self): super(OmniFieldInstanceTestCase, self).setUp() self.field = OmniFloatField( name='Test Field', label='Test Field Label', help_text='Test help text', required=True, widget_class='django.forms.widgets.TextInput', form=self.omni_form ) self.field.save()
def test_form_widgets(self): """ The model should define the correct form widgets """ self.assertIn('django.forms.widgets.TextInput', OmniCharField.FORM_WIDGETS) self.assertIn('django.forms.widgets.Textarea', OmniCharField.FORM_WIDGETS) self.assertIn('django.forms.widgets.PasswordInput', OmniCharField.FORM_WIDGETS)
def test_form_widgets(self): """ The model should define the correct form widgets """ self.assertIn('django.forms.widgets.TextInput', OmniDurationField.FORM_WIDGETS) self.assertIn('django.forms.widgets.Textarea', OmniDurationField.FORM_WIDGETS)
def test_form_widgets(self): """ The model should define the correct form widgets """ self.assertIn('django.forms.widgets.TextInput', OmniGenericIPAddressField.FORM_WIDGETS)
def test_form_widgets(self): """ The model should define the correct form widgets """ self.assertIn('django.forms.widgets.TextInput', OmniSlugField.FORM_WIDGETS) self.assertIn('django.forms.widgets.HiddenInput', OmniSlugField.FORM_WIDGETS)
def formfield(self, **kwargs): defaults = {'widget': forms.TextInput} defaults.update(kwargs) return super(VarCharField, self).formfield(**defaults)
def __init__(self, attrs=None, model=User, opt={}): _widgets = ( forms.widgets.TextInput(attrs=opt.get('text_attr', {})), forms.HiddenInput() ) self.model = model super(AutocompleteWidget, self).__init__(_widgets, attrs)