Python django.forms.TextInput() Examples

The following are 30 code examples for showing how to use django.forms.TextInput(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.forms , or try the search function .

Example 1
Project: Servo   Author: fpsw   File: checkin.py    License: 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 2
Project: coursys   Author: sfu-fas   File: text.py    License: 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 3
Project: django-better-admin-arrayfield   Author: gradam   File: widgets.py    License: 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 4
Project: casepro   Author: rapidpro   File: forms.py    License: 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 5
Project: pasportaservo   Author: tejoesperanto   File: forms.py    License: 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 6
Project: Django-blog   Author: enjoy-binbin   File: forms.py    License: MIT License 6 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 7
Project: online-judge   Author: DMOJ   File: runtime.py    License: 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 8
Project: janeway   Author: BirkbeckCTP   File: forms.py    License: 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 9
Project: wagtail   Author: wagtail   File: test_blocks.py    License: 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 10
Project: GraphSpace   Author: Murali-group   File: forms.py    License: 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 11
Project: django-userena-ce   Author: django-userena-ce   File: forms.py    License: 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 12
Project: Dailyfresh-B2C   Author: BeanWei   File: widgets.py    License: Apache License 2.0 6 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 13
Project: freedomvote   Author: freedomvote   File: forms.py    License: GNU General Public License v3.0 6 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 14
Project: djongo   Author: nesdis   File: test_media.py    License: 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 15
Project: djongo   Author: nesdis   File: tests.py    License: 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 16
Project: Servo   Author: fpsw   File: base.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(TextInput, self).__init__(*args, **kwargs)
        self.attrs['class'] = 'span12' 
Example 17
Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        class MockForm(forms.Form):
            enabled_field = forms.CharField()
            disabled_field = forms.CharField(
                widget=forms.TextInput(attrs={'disabled': True}))
        self.form_class = MockForm
        self.form = self.form_class() 
Example 18
Project: django-accounting   Author: dulacp   File: template_tags_tests.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        class MockForm(forms.Form):
            writable_field = forms.CharField()
            readonly_field = forms.CharField(
                widget=forms.TextInput(attrs={'readonly': True}))
        self.form_class = MockForm
        self.form = self.form_class() 
Example 19
Project: coursys   Author: sfu-fas   File: mc.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, n=10, *args, **kwargs):
        self.n = n
        choice_widgets = [
            forms.TextInput(attrs={'class': 'mc-choice'})
            for _ in range(self.n)
        ]
        mark_widgets = [
            forms.TextInput(attrs={'class': 'mc-mark'})
            for _ in range(self.n)
        ]
        super().__init__(widgets=(choice_widgets + mark_widgets), *args, **kwargs) 
Example 20
Project: coursys   Author: sfu-fas   File: forms.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.widget = forms.TextInput(attrs={'size': 60})
        if 'required' not in kwargs:
            kwargs['required'] = False
        if 'help_text' not in kwargs:
            kwargs['help_text'] = 'Comment on this change'
        super(CommentField, self).__init__(*args, **kwargs) 
Example 21
Project: coursys   Author: sfu-fas   File: widgets.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, attrs=None, max=20, min=1 ):
        self.max = int(max)
        self.min = int(min)

        widgets = [forms.TextInput() for _ in range(self.max)]

        super(CustomMultipleInputWidget, self).__init__(widgets, attrs=attrs) 
Example 22
Project: coursys   Author: sfu-fas   File: widgets.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        widget = forms.TextInput(attrs={'class': 'autocomplete_person'})
        kwargs['widget'] = widget
        if 'initial' in kwargs:
            kwargs['initial'] = Person.objects.get(id=kwargs['initial']).emplid
        super(PersonField, self).__init__(*args, **kwargs) 
Example 23
Project: coursys   Author: sfu-fas   File: fields.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, attrs=None, mode=0, semester_start=True):
        self.semester_start = semester_start
        semester_attrs = attrs or {}
        semester_attrs.update({"maxlength": 4, "size": 6, "class": "semester-input"})
        if self.semester_start:
            semester_attrs.update({"class": "semester-input semester-start"})
        date_attrs = {"class": "date-input"}
        _widgets = (
            forms.widgets.DateInput(attrs=date_attrs),
            forms.widgets.TextInput(attrs=semester_attrs),
        )
        super(SemesterDateInput, self).__init__(_widgets, attrs) 
Example 24
Project: coursys   Author: sfu-fas   File: fields.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, start=True, **kwargs):
        defaults = {
            'help_text': mark_safe('Enter semester code, e.g.: 1141'),
            'label': '{} Semester'.format(start and 'Starting' or 'Ending'),
            'widget': forms.TextInput(attrs={'size': 4}),
        }
        defaults.update(kwargs)
        super(SemesterToDateField, self).__init__(min_length=4, max_length=4, **defaults)
        self.start = start 
Example 25
Project: coursys   Author: sfu-fas   File: fields.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, **kwargs):
        defaults = {
            'help_text': mark_safe('Enter semester code, e.g.: 1141'),
            'widget': forms.TextInput(attrs={'size': 4}),
        }
        defaults.update(kwargs)
        super(SemesterCodeField, self).__init__(min_length=4, max_length=4, **defaults) 
Example 26
Project: coursys   Author: sfu-fas   File: forms.py    License: GNU General Public License v3.0 5 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 27
Project: coursys   Author: sfu-fas   File: forms.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        widgets = [forms.TextInput(attrs={'size': 6}) for _ in CATEGORY_CHOICES]
        kwargs['widgets'] = widgets
        super(PayWidget, self).__init__(*args, **kwargs) 
Example 28
Project: heltour   Author: cyanfish   File: models.py    License: MIT License 5 votes vote down vote up
def formfield(self, **kwargs):
        defaults = {'widget': django_forms.TextInput(attrs={'class': 'vIntegerField'}),
                    'initial': self.default}
        defaults.update(kwargs)
        return django_forms.FloatField(**defaults)


# ------------------------------------------------------------------------------- 
Example 29
Project: waliki   Author: mgaitan   File: forms.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        is_hidden = kwargs.pop('is_hidden', None)
        super(PageForm, self).__init__(*args, **kwargs)
        self.fields['raw'].initial = self.instance.raw
        self.fields['markup'].widget = forms.HiddenInput()
        self.fields['message'].widget = forms.TextInput(attrs={'placeholder': _('Update %s') % self.instance.path})
        if is_hidden:
            for field in self.fields.values():
                field.widget = forms.HiddenInput() 
Example 30
Project: BikeMaps   Author: SPARLab   File: widgets.py    License: MIT License 5 votes vote down vote up
def __init__(self, attrs=None, choices=()):
        # choices is some iterable we do not need, since this is a TextInput
        super(MultipleInput, self).__init__(attrs)