Python django.forms.widgets.TextInput() Examples

The following are 27 code examples of django.forms.widgets.TextInput(). 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.widgets , or try the search function .
Example #1
Source File: forms.py    From Django-blog with MIT License 10 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 只修改widget
        self.fields['username'].widget = widgets.TextInput(
            attrs={
                'placeholder': 'Username',
                'class': 'form-control',
                'style': 'margin-bottom: 10px'
            })
        self.fields['email'].widget = widgets.EmailInput(
            attrs={
                'placeholder': 'Email',
                'class': 'form-control'
            })
        self.fields['password1'].widget = widgets.PasswordInput(
            attrs={
                'placeholder': 'New password',
                'class': 'form-control'
            })
        self.fields['password2'].widget = widgets.PasswordInput(
            attrs={
                'placeholder': 'Repeat password',
                'class': 'form-control'
            }) 
Example #2
Source File: bootstrap_toolkit.py    From yats with MIT License 6 votes vote down vote up
def bootstrap_input_type(field):
    """
    Return input type to use for field
    """
    try:
        widget = field.field.widget
    except:
        raise ValueError("Expected a Field, got a %s" % type(field))
    input_type = getattr(widget, 'bootstrap_input_type', None)
    if input_type:
        return str(input_type)
    if isinstance(widget, TextInput):
        return u'text'
    if isinstance(widget, CheckboxInput):
        return u'checkbox'
    if isinstance(widget, CheckboxSelectMultiple):
        return u'multicheckbox'
    if isinstance(widget, RadioSelect):
        return u'radioset'
    return u'default' 
Example #3
Source File: test_config_forms.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_DictCharWidget_renders_with_initial_when_no_value(self):
        """Widgets should use initial value if rendered without value."""
        names = [factory.make_name()]
        initials = [factory.make_name()]
        labels = [factory.make_name()]
        mock_widget = Mock()
        mock_widget.configure_mock(**{"render.return_value": ""})
        widget = DictCharWidget(
            [mock_widget, widgets.TextInput],
            names,
            initials,
            labels,
            skip_check=True,
        )
        widget.render("foo", [])

        self.assertThat(
            mock_widget.render, MockCalledOnceWith(ANY, initials[0], ANY)
        ) 
Example #4
Source File: test_config_forms.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_DictCharWidget_renders_with_empty_string_as_input_data(self):
        names = [factory.make_string(), factory.make_string()]
        initials = []
        labels = [factory.make_string(), factory.make_string()]
        widget = DictCharWidget(
            [widgets.TextInput, widgets.TextInput, widgets.CheckboxInput],
            names,
            initials,
            labels,
            skip_check=True,
        )
        name = factory.make_string()
        html_widget = fromstring(
            "<root>" + widget.render(name, "") + "</root>"
        )
        widget_names = XPath("fieldset/input/@name")(html_widget)
        widget_labels = XPath("fieldset/label/text()")(html_widget)
        expected_names = [
            "%s_%s" % (name, widget_name) for widget_name in names
        ]
        self.assertEqual(
            [expected_names, labels], [widget_names, widget_labels]
        ) 
Example #5
Source File: test_cluster_form.py    From django-modelcluster with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_widgets_with_media(self):
        class WidgetWithMedia(TextInput):
            class Media:
                js = ['test.js']
                css = {'all': ['test.css']}

        class FormWithWidgetMedia(ClusterForm):
            class Meta:
                model = Restaurant
                fields = ['name', 'tags', 'serves_hot_dogs', 'proprietor']
                widgets = {
                    'name': WidgetWithMedia
                }

        form = FormWithWidgetMedia()

        self.assertIn('test.js', str(form.media['js']))
        self.assertIn('test.css', str(form.media['css'])) 
Example #6
Source File: forms.py    From Django-blog with MIT License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['username'].widget = widgets.TextInput(
            attrs={
                'placeholder': 'Username',
                'class': 'form-control',
                'style': 'margin-bottom: 10px',
                'autofocus': True
            })
        self.fields['password'].widget = widgets.PasswordInput(
            attrs={
                'placeholder': 'Password',
                'class': 'form-control'
            }
        ) 
Example #7
Source File: widgets.py    From django-places with MIT License 6 votes vote down vote up
def __init__(self, attrs=None):
        _widgets = (
            widgets.TextInput(
                attrs={'data-geo': 'formatted_address', 'data-id': 'map_place'}
            ),
            widgets.TextInput(
                attrs={
                    'data-geo': 'lat',
                    'data-id': 'map_latitude',
                    'placeholder': _('Latitude'),
                }
            ),
            widgets.TextInput(
                attrs={
                    'data-geo': 'lng',
                    'data-id': 'map_longitude',
                    'placeholder': _('Longitude'),
                }
            ),
        )
        super(PlacesWidget, self).__init__(_widgets, attrs) 
Example #8
Source File: widgets.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, attrs=None):
        _widgets = (
            widgets.TextInput(),
            LabeledCheckboxInput(label="Include CommonName")
        )
        super(SubjectAltNameWidget, self).__init__(_widgets, attrs) 
Example #9
Source File: forms.py    From steemprojects.com with MIT License 5 votes vote down vote up
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"
        }) 
Example #10
Source File: test_config_forms.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_DictCharWidget_value_from_datadict_values_from_data(self):
        # 'value_from_datadict' extracts the values corresponding to the
        # field as a dictionary.
        names = [factory.make_string(), factory.make_string()]
        initials = []
        labels = [factory.make_string(), factory.make_string()]
        name = factory.make_string()
        field_1_value = factory.make_string()
        field_2_value = factory.make_string()
        # Create a query string with the field2 before the field1 and another
        # (unknown) value.
        data = QueryDict(
            "%s_%s=%s&%s_%s=%s&%s=%s"
            % (
                name,
                names[1],
                field_2_value,
                name,
                names[0],
                field_1_value,
                factory.make_string(),
                factory.make_string(),
            )
        )
        widget = DictCharWidget(
            [widgets.TextInput, widgets.TextInput], names, initials, labels
        )
        self.assertEqual(
            {names[0]: field_1_value, names[1]: field_2_value},
            widget.value_from_datadict(data, None, name),
        ) 
Example #11
Source File: test_config_forms.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_DictCharWidget_renders_fieldset_with_label_and_field_names(self):
        names = [factory.make_string(), factory.make_string()]
        initials = []
        labels = [factory.make_string(), factory.make_string()]
        values = [factory.make_string(), factory.make_string()]
        widget = DictCharWidget(
            [widgets.TextInput, widgets.TextInput, widgets.CheckboxInput],
            names,
            initials,
            labels,
            skip_check=True,
        )
        name = factory.make_string()
        html_widget = fromstring(
            "<root>" + widget.render(name, values) + "</root>"
        )
        widget_names = XPath("fieldset/input/@name")(html_widget)
        widget_labels = XPath("fieldset/label/text()")(html_widget)
        widget_values = XPath("fieldset/input/@value")(html_widget)
        expected_names = [
            "%s_%s" % (name, widget_name) for widget_name in names
        ]
        self.assertEqual(
            [expected_names, labels, values],
            [widget_names, widget_labels, widget_values],
        ) 
Example #12
Source File: test_config_forms.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_DictCharWidget_id_for_label_uses_first_fields_name(self):
        names = [factory.make_string()]
        initials = []
        labels = [factory.make_string()]
        widget = DictCharWidget(
            [widgets.TextInput, widgets.TextInput], names, initials, labels
        )
        self.assertEqual(" _%s" % names[0], widget.id_for_label(" ")) 
Example #13
Source File: tests.py    From avos with Apache License 2.0 5 votes vote down vote up
def test_edit_attachments_auto_device_name(self):
        volume = self.cinder_volumes.first()
        servers = [s for s in self.servers.list()
                   if s.tenant_id == self.request.user.tenant_id]
        volume.attachments = [{'id': volume.id,
                               'volume_id': volume.id,
                               'volume_name': volume.name,
                               'instance': servers[0],
                               'device': '',
                               'server_id': servers[0].id}]

        cinder.volume_get(IsA(http.HttpRequest), volume.id).AndReturn(volume)
        api.nova.server_list(IsA(http.HttpRequest)).AndReturn([servers, False])
        self.mox.ReplayAll()

        url = reverse('horizon:project:volumes:volumes:attach',
                      args=[volume.id])
        res = self.client.get(url)
        form = res.context['form']
        self.assertTrue(isinstance(form.fields['device'].widget,
                                   widgets.TextInput))
        self.assertFalse(form.fields['device'].required) 
Example #14
Source File: tests.py    From avos with Apache License 2.0 5 votes vote down vote up
def test_edit_attachments(self):
        volume = self.cinder_volumes.first()
        servers = [s for s in self.servers.list()
                   if s.tenant_id == self.request.user.tenant_id]
        volume.attachments = [{'id': volume.id,
                               'volume_id': volume.id,
                               'volume_name': volume.name,
                               'instance': servers[0],
                               'device': '/dev/vdb',
                               'server_id': servers[0].id}]

        cinder.volume_get(IsA(http.HttpRequest), volume.id).AndReturn(volume)
        api.nova.server_list(IsA(http.HttpRequest)).AndReturn([servers, False])
        self.mox.ReplayAll()

        url = reverse('horizon:project:volumes:volumes:attach',
                      args=[volume.id])
        res = self.client.get(url)
        msg = 'Volume %s on instance %s' % (volume.name, servers[0].name)
        self.assertContains(res, msg)
        # Asserting length of 2 accounts for the one instance option,
        # and the one 'Choose Instance' option.
        form = res.context['form']
        self.assertEqual(len(form.fields['instance']._choices),
                         1)
        self.assertEqual(res.status_code, 200)
        self.assertTrue(isinstance(form.fields['device'].widget,
                                   widgets.TextInput))
        self.assertFalse(form.fields['device'].required) 
Example #15
Source File: tests.py    From avos with Apache License 2.0 5 votes vote down vote up
def test_launch_form_instance_device_name_showed(self):
        self._test_launch_form_instance_show_device_name(
            u'vda', widgets.TextInput, {
                'name': 'device_name', 'value': 'vda',
                'attrs': {'id': 'id_device_name'}}
        ) 
Example #16
Source File: widgets.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def textinfo(cls, choice):
        attrs = {
            "placeholder": choice.get("extra_info_text"),
            "class": "extra-widget extra-widget-text",
            "style": "display: none;",
        }
        return Field(required=False, widget=TextInput(attrs=attrs)) 
Example #17
Source File: boundfield.py    From python2017 with MIT License 5 votes vote down vote up
def as_text(self, attrs=None, **kwargs):
        """
        Returns a string of HTML for representing this as an <input type="text">.
        """
        return self.as_widget(TextInput(), attrs, **kwargs) 
Example #18
Source File: boundfield.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def as_text(self, attrs=None, **kwargs):
        """
        Returns a string of HTML for representing this as an <input type="text">.
        """
        return self.as_widget(TextInput(), attrs, **kwargs) 
Example #19
Source File: forms.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def as_text(self, attrs=None, **kwargs):
        """
        Returns a string of HTML for representing this as an <input type="text">.
        """
        return self.as_widget(TextInput(), attrs, **kwargs) 
Example #20
Source File: boundfield.py    From python with Apache License 2.0 5 votes vote down vote up
def as_text(self, attrs=None, **kwargs):
        """
        Returns a string of HTML for representing this as an <input type="text">.
        """
        return self.as_widget(TextInput(), attrs, **kwargs) 
Example #21
Source File: boundfield.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def as_text(self, attrs=None, **kwargs):
        """
        Return a string of HTML for representing this as an <input type="text">.
        """
        return self.as_widget(TextInput(), attrs, **kwargs) 
Example #22
Source File: test_cluster_form.py    From django-modelcluster with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_widgets_with_media_on_child_form(self):
        """
        The media property of ClusterForm should pick up media defined on child forms too
        """
        class FancyTextInput(TextInput):
            class Media:
                js = ['fancy-text-input.js']

        class FancyFileUploader(FileInput):
            class Media:
                js = ['fancy-file-uploader.js']

        class FormWithWidgetMedia(ClusterForm):
            class Meta:
                model = Gallery
                fields = ['title']
                widgets = {
                    'title': FancyTextInput,
                }

                formsets = {
                    'images': {
                        'fields': ['image'],
                        'widgets': {'image': FancyFileUploader}
                    }
                }

        form = FormWithWidgetMedia()

        self.assertIn('fancy-text-input.js', str(form.media['js']))
        self.assertIn('fancy-file-uploader.js', str(form.media['js'])) 
Example #23
Source File: boundfield.py    From bioforum with MIT License 5 votes vote down vote up
def as_text(self, attrs=None, **kwargs):
        """
        Return a string of HTML for representing this as an <input type="text">.
        """
        return self.as_widget(TextInput(), attrs, **kwargs) 
Example #24
Source File: forms.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def as_text(self, attrs=None, **kwargs):
        """
        Returns a string of HTML for representing this as an <input type="text">.
        """
        return self.as_widget(TextInput(), attrs, **kwargs) 
Example #25
Source File: codefile.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
            super(Codefile.ComponentForm, self).__init__(*args, **kwargs)
            self.fields['description'].widget = Textarea(attrs={'cols': 50, 'rows': 5})
            self.fields['max_size'].widget = TextInput(attrs={'style':'width:5em'})
            del self.fields['specified_filename'] # our filename and filename.type do a better job 
Example #26
Source File: code.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
            super(Code.ComponentForm, self).__init__(*args, **kwargs)
            self.fields['description'].widget = Textarea(attrs={'cols': 50, 'rows': 5})
            self.fields['max_size'].widget = TextInput(attrs={'style':'width:5em'})
            self.fields['allowed'].widget = SelectMultiple(choices=CODE_TYPES, attrs={'style':'width:40em', 'size': 15})
            self.initial['allowed'] = self._initial_allowed 
Example #27
Source File: widgets.py    From adhocracy4 with GNU Affero General Public License v3.0 4 votes vote down vote up
def render(self, name, value, attrs=None, renderer=None):
        html_id = attrs and attrs.get('id', name) or name
        has_image_set = self.is_initial(value)
        is_required = self.is_required

        file_placeholder = ugettext('Select a picture from your local folder.')
        file_input = super().render(name, None, {
            'id': html_id,
            'class': 'form-control form-control-file'
        })

        if has_image_set:
            file_name = basename(value.name)
            file_url = conditional_escape(value.url)
        else:
            file_name = ""
            file_url = ""

        text_input = widgets.TextInput().render('__noname__', file_name, {
            'class': 'form-control form-control-file-dummy',
            'placeholder': file_placeholder,
            'tabindex': '-1',
            'id': 'text-{}'.format(html_id)
        })

        checkbox_id = self.clear_checkbox_id(name)
        checkbox_name = self.clear_checkbox_name(name)
        checkbox_input = widgets.CheckboxInput().render(checkbox_name, False, {
            'id': checkbox_id,
            'class': 'clear-image',
            'data-upload-clear': html_id,
        })

        context = {
            'id': html_id,
            'has_image_set': has_image_set,
            'is_required': is_required,
            'file_url': file_url,
            'file_input': file_input,
            'file_id': html_id + '-file',
            'text_input': text_input,
            'checkbox_input': checkbox_input,
            'checkbox_id': checkbox_id
        }

        return loader.render_to_string(
            'a4images/image_upload_widget.html',
            context
        )