Python django.forms.TextInput() Examples

The following are 30 code examples of django.forms.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 , 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: widgets.py    From Dailyfresh-B2C with Apache License 2.0 7 votes vote down vote up
def render(self, name, value, attrs=None):
        if not self._isiterable(value):
            value = [value]

        if len(value) <= 1:
            # delegate to main widget (Select, etc...) if not multiple values
            value = value[0] if value else ''
            return super(BaseCSVWidget, self).render(name, value, attrs)

        # if we have multiple values, we need to force render as a text input
        # (otherwise, the additional values are lost)
        surrogate = forms.TextInput()
        value = [force_text(format_value(surrogate, v)) for v in value]
        value = ','.join(list(value))

        return surrogate.render(name, value, attrs) 
Example #3
Source File: forms.py    From freedomvote with GNU General Public License v3.0 7 votes vote down vote up
def __init__(self, *args, **kwargs):
        kwargs.setdefault('label_suffix', '')
        super(PoliticianForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            if isinstance(field.widget, forms.TextInput) or isinstance(field.widget, forms.Select) or isinstance(field.widget, forms.EmailInput):
                field.widget.attrs.update({
                    'class': 'form-control'
                })
            if field_name == 'party':
                field.choices = [('', '---------')]
                field.choices += [
                    (p.id, p.name)
                    for p
                    in Party.objects.order_by('name')
                ]

            if isinstance(field.widget, forms.Textarea):
                field.widget.attrs.update({
                    'class': 'form-control',
                    'rows': 2,
                }) 
Example #4
Source File: checkin.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, *args, **kwargs):

        super(DeviceForm, self).__init__(*args, **kwargs)

        if Configuration.false('checkin_require_password'):
            self.fields['password'].required = False

        if Configuration.true('checkin_require_condition'):
            self.fields['condition'].required = True

        if kwargs.get('instance'):
            prod = gsxws.Product('')
            prod.description = self.instance.description

            if prod.is_ios:
                self.fields['password'].label = _('Passcode')

            if not prod.is_ios:
                del(self.fields['imei'])
            if not prod.is_mac:
                del(self.fields['username'])

        if Configuration.true('checkin_password'):
            self.fields['password'].widget = forms.TextInput(attrs={'class': 'span12'}) 
Example #5
Source File: runtime.py    From online-judge with GNU Affero General Public License v3.0 6 votes vote down vote up
def render(self, name, value, attrs=None, renderer=None):
        text = super(TextInput, self).render(name, value, attrs)
        return mark_safe(text + format_html(
            '''\
<a href="#" onclick="return false;" class="button" id="id_{0}_regen">Regenerate</a>
<script type="text/javascript">
django.jQuery(document).ready(function ($) {{
    $('#id_{0}_regen').click(function () {{
        var length = 100,
            charset = "abcdefghijklnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()_+-=|[]{{}};:,<>./?",
            key = "";
        for (var i = 0, n = charset.length; i < length; ++i) {{
            key += charset.charAt(Math.floor(Math.random() * n));
        }}
        $('#id_{0}').val(key);
    }});
}});
</script>
''', name)) 
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: forms.py    From janeway with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        key_type = kwargs.pop('key_type', None)
        value = kwargs.pop('value', None)
        super(EditKey, self).__init__(*args, **kwargs)

        if key_type == 'rich-text':
            self.fields['value'].widget = SummernoteWidget()
        elif key_type == 'boolean':
            self.fields['value'].widget = forms.CheckboxInput()
        elif key_type == 'integer':
            self.fields['value'].widget = forms.TextInput(attrs={'type': 'number'})
        elif key_type == 'file' or key_type == 'journalthumb':
            self.fields['value'].widget = forms.FileInput()
        elif key_type == 'text':
            self.fields['value'].widget = forms.Textarea()
        else:
            self.fields['value'].widget.attrs['size'] = '100%'

        self.fields['value'].initial = value
        self.fields['value'].required = False 
Example #8
Source File: test_media.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_multi_media(self):
        ###############################################################
        # Multi-media handling for CSS
        ###############################################################

        # A widget can define CSS media for multiple output media types
        class MultimediaWidget(TextInput):
            class Media:
                css = {
                    'screen, print': ('/file1', '/file2'),
                    'screen': ('/file3',),
                    'print': ('/file4',)
                }
                js = ('/path/to/js1', '/path/to/js4')

        multimedia = MultimediaWidget()
        self.assertEqual(
            str(multimedia.media),
            """<link href="/file4" type="text/css" media="print" rel="stylesheet">
<link href="/file3" type="text/css" media="screen" rel="stylesheet">
<link href="/file1" type="text/css" media="screen, print" rel="stylesheet">
<link href="/file2" type="text/css" media="screen, print" rel="stylesheet">
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="/path/to/js4"></script>"""
        ) 
Example #9
Source File: forms.py    From pasportaservo with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        is_in_book = kwargs.pop('is_in_book')
        self.user = kwargs.pop('user')
        self.product = kwargs.pop('product')
        super().__init__(*args, **kwargs)

        self.fields['in_book'].initial = is_in_book
        self.fields['in_book'].widget.attrs.update({
            'data-bind': "checked: inBook"})
        self.fields['amount'].widget.attrs.update({
            'class': "form-control input-lg text-center",
            'data-bind': "textInput: productAmount"})
        self.fields['discount'].widget.attrs['data-bind'] = "checked: hasTejoDiscount, cli"
        self.fields['support'].localize = True
        self.fields['support'].widget = forms.TextInput(attrs={
            'class': "form-control pull-right same-as-body",
            'style': "width: 5em; text-align: right; padding-right: calc(1em - 1px)",
            'pattern': "[0-9]{1,4},[0-9]{2}",
            'data-bind': "textInput: supportInput"}) 
Example #10
Source File: test_blocks.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_widget_media(self):
        class CalendarWidget(forms.TextInput):
            @property
            def media(self):
                return forms.Media(
                    css={'all': ('pretty.css',)},
                    js=('animations.js', 'actions.js')
                )

        class CalenderBlock(blocks.FieldBlock):
            def __init__(self, required=True, help_text=None, max_length=None, min_length=None, **kwargs):
                # Set widget to CalenderWidget
                self.field = forms.CharField(
                    required=required,
                    help_text=help_text,
                    max_length=max_length,
                    min_length=min_length,
                    widget=CalendarWidget(),
                )
                super(blocks.FieldBlock, self).__init__(**kwargs)

        block = CalenderBlock()
        self.assertIn('pretty.css', ''.join(block.all_media().render_css()))
        self.assertIn('animations.js', ''.join(block.all_media().render_js())) 
Example #11
Source File: forms.py    From casepro with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        org = kwargs.pop("org")
        is_create = kwargs.pop("is_create")

        super(LabelForm, self).__init__(*args, **kwargs)

        # don't let users change names of existing labels
        if not is_create:
            self.fields["name"].widget = forms.TextInput(attrs={"readonly": "readonly"})

        self.fields["groups"].queryset = Group.get_all(org).order_by("name")

        self.fields["field_test"] = FieldTestField(
            org=org,
            label=_("Field criteria"),
            required=False,
            help_text=_("Match messages where contact field value is equal to any of these values (comma separated)"),
        ) 
Example #12
Source File: widgets.py    From django-better-admin-arrayfield with MIT License 6 votes vote down vote up
def get_context(self, name, value, attrs):
        context_value = value or [""]
        context = super().get_context(name, context_value, attrs)
        final_attrs = context["widget"]["attrs"]
        id_ = context["widget"]["attrs"].get("id")
        context["widget"]["is_none"] = value is None

        subwidgets = []
        for index, item in enumerate(context["widget"]["value"]):
            widget_attrs = final_attrs.copy()
            if id_:
                widget_attrs["id"] = "{id_}_{index}".format(id_=id_, index=index)
            widget = forms.TextInput()
            widget.is_required = self.is_required
            subwidgets.append(widget.get_context(name, item, widget_attrs)["widget"])

        context["widget"]["subwidgets"] = subwidgets
        return context 
Example #13
Source File: forms.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        widgets = [forms.Select(), forms.TextInput(attrs={'size': 8, 'maxlength': 8})]
        kwargs['widgets'] = widgets
        super(SupervisorWidget, self).__init__(*args, **kwargs) 
Example #14
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_formfield_overrides_widget_instances(self):
        """
        Widget instances in formfield_overrides are not shared between
        different fields. (#19423)
        """
        class BandAdmin(admin.ModelAdmin):
            formfield_overrides = {
                CharField: {'widget': forms.TextInput(attrs={'size': '10'})}
            }
        ma = BandAdmin(Band, admin.site)
        f1 = ma.formfield_for_dbfield(Band._meta.get_field('name'), request=None)
        f2 = ma.formfield_for_dbfield(Band._meta.get_field('style'), request=None)
        self.assertNotEqual(f1.widget, f2.widget)
        self.assertEqual(f1.widget.attrs['maxlength'], '100')
        self.assertEqual(f2.widget.attrs['maxlength'], '20')
        self.assertEqual(f2.widget.attrs['size'], '10') 
Example #15
Source File: text.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def make_entry_field(self, fieldsubmission=None):
        self.min_length = 0
        self.max_length = 0

        if self.config['min_length'] and int(self.config['min_length']) > 0:
            self.min_length = int(self.config['min_length'])
        if self.config['max_length'] and int(self.config['max_length']) > 0:
            self.max_length = int(self.config['max_length'])

        c = forms.CharField(required=self.config['required'],
            widget=forms.TextInput(attrs=
                {'size': min(self.config.get('size', 60), int(self.config['max_length'])),
                 'maxlength': int(self.config['max_length'])}),
            label=self.config['label'],
            help_text=self.config['help_text'],
            min_length=self.min_length,
            max_length=self.max_length)

        if fieldsubmission:
            c.initial = fieldsubmission.data['info']

        return c 
Example #16
Source File: forms.py    From GraphSpace with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
		"""
			Initialize the form. A keyword argument 'placeholder' may be
			given.

			This can be customized to specify additional parameters if it
			needs to.
		"""
		if 'placeholder' in kwargs:
			self.placeholder = kwargs.pop('placeholder')
			# must be called after 'placeholder' is popped from kwargs
			super(SearchForm, self).__init__(*args, **kwargs)
			self.fields['search'].widget = forms.TextInput(attrs={'placeholder': self.placeholder, 'class': 'form-control', 'type': 'text', 'name': 'search'})
		else:
			super(SearchForm, self).__init__(*args, **kwargs)
			self.fields['search'].widget = forms.TextInput(attrs={'class': 'form-control', 'type': 'text', 'name': 'search'}) 
Example #17
Source File: forms.py    From django-userena-ce with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def identification_field_factory(label, error_required):
    """
    A simple identification field factory which enable you to set the label.

    :param label:
        String containing the label for this field.

    :param error_required:
        String containing the error message if the field is left empty.

    """
    return forms.CharField(
        label=label,
        widget=forms.TextInput(attrs=attrs_dict),
        max_length=75,
        error_messages={"required": error_required},
    ) 
Example #18
Source File: test_textinput.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_attrs_safestring(self):
        widget = TextInput(attrs={'onBlur': mark_safe("function('foo')")})
        self.check_html(widget, 'email', '', html='<input onBlur="function(\'foo\')" type="text" name="email">') 
Example #19
Source File: test_textinput.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_attrs_precedence(self):
        """
        `attrs` passed to render() get precedence over those passed to the
        constructor
        """
        widget = TextInput(attrs={'class': 'pretty'})
        self.check_html(
            widget, 'email', '', attrs={'class': 'special'},
            html='<input type="text" class="special" name="email">',
        ) 
Example #20
Source File: test_textinput.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_constructor_attrs(self):
        widget = TextInput(attrs={'class': 'fun', 'type': 'email'})
        self.check_html(widget, 'email', '', html='<input type="email" class="fun" name="email">')
        self.check_html(
            widget, 'email', 'foo@example.com',
            html='<input type="email" class="fun" value="foo@example.com" name="email">',
        ) 
Example #21
Source File: widgets.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def __init__(self, attrs=None):
        widgets = (forms.TextInput, forms.TextInput)
        super(RangeWidget, self).__init__(widgets, attrs) 
Example #22
Source File: test_media.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_media_dsl(self):
        ###############################################################
        # DSL Class-based media definitions
        ###############################################################

        # A widget can define media if it needs to.
        # Any absolute path will be preserved; relative paths are combined
        # with the value of settings.MEDIA_URL
        class MyWidget1(TextInput):
            class Media:
                css = {
                    'all': ('path/to/css1', '/path/to/css2')
                }
                js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')

        w1 = MyWidget1()
        self.assertEqual(
            str(w1.media),
            """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet">
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>"""
        )

        # Media objects can be interrogated by media type
        self.assertEqual(
            str(w1.media['css']),
            """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet">
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">"""
        )

        self.assertEqual(
            str(w1.media['js']),
            """<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="http://media.other.com/path/to/js2"></script>
<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>"""
        ) 
Example #23
Source File: test_textinput.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_attrs_safestring(self):
        widget = TextInput(attrs={'onBlur': mark_safe("function('foo')")})
        self.check_html(widget, 'email', '', html='<input onBlur="function(\'foo\')" type="text" name="email">') 
Example #24
Source File: test_media.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_media_inheritance_single_type(self):
        # A widget can enable inheritance of one media type by specifying extend as a tuple
        class MyWidget1(TextInput):
            class Media:
                css = {
                    'all': ('path/to/css1', '/path/to/css2')
                }
                js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')

        class MyWidget12(MyWidget1):
            class Media:
                extend = ('css',)
                css = {
                    'all': ('/path/to/css3', 'path/to/css1')
                }
                js = ('/path/to/js1', '/path/to/js4')

        w12 = MyWidget12()
        self.assertEqual(
            str(w12.media),
            """<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">
<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet">
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">
<script type="text/javascript" src="/path/to/js1"></script>
<script type="text/javascript" src="/path/to/js4"></script>"""
        ) 
Example #25
Source File: forms.py    From freedomvote with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        kwargs.setdefault('label_suffix', '')
        super(PartyPoliticianForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            if isinstance(field.widget, forms.TextInput) or isinstance(field.widget, forms.Select):
                field.widget.attrs.update({
                    'class': 'form-control'
                }) 
Example #26
Source File: test_textinput.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_attrs_precedence(self):
        """
        `attrs` passed to render() get precedence over those passed to the
        constructor
        """
        widget = TextInput(attrs={'class': 'pretty'})
        self.check_html(
            widget, 'email', '', attrs={'class': 'special'},
            html='<input type="text" class="special" name="email">',
        ) 
Example #27
Source File: views.py    From elearning with MIT License 5 votes vote down vote up
def get_form(self, model, *args, **kwargs):
        Form = modelform_factory(model, exclude=['owner', 'order', 'created', 'updated'], widgets={'title': forms.TextInput(attrs={'class':'form-control'}), 'content': forms.Textarea(attrs={'class':'form-control', 'cols': 40, 'rows': 8}), 'url': forms.TextInput(attrs={'class':'form-control'})})

        return Form(*args, **kwargs) 
Example #28
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_modelformset_factory_widgets(self):
        widgets = {
            'name': forms.TextInput(attrs={'class': 'poet'})
        }
        PoetFormSet = modelformset_factory(Poet, fields="__all__", widgets=widgets)
        form = PoetFormSet.form()
        self.assertHTMLEqual(
            "%s" % form['name'],
            '<input id="id_name" maxlength="100" type="text" class="poet" name="name" required>'
        ) 
Example #29
Source File: test_textinput.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_constructor_attrs(self):
        widget = TextInput(attrs={'class': 'fun', 'type': 'email'})
        self.check_html(widget, 'email', '', html='<input type="email" class="fun" name="email">')
        self.check_html(
            widget, 'email', 'foo@example.com',
            html='<input type="email" class="fun" value="foo@example.com" name="email">',
        ) 
Example #30
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_inlineformset_factory_widgets(self):
        widgets = {
            'title': forms.TextInput(attrs={'class': 'book'})
        }
        BookFormSet = inlineformset_factory(Author, Book, widgets=widgets, fields="__all__")
        form = BookFormSet.form()
        self.assertHTMLEqual(
            "%s" % form['title'],
            '<input class="book" id="id_title" maxlength="100" name="title" type="text" required>'
        )