Python django.forms.Textarea() Examples

The following are 30 code examples for showing how to use django.forms.Textarea(). 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: 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.Textarea(attrs={'cols': '60', 'rows': self.config.get('rows', '3')}),
            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 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.Textarea(attrs={'cols': '60', 'rows': self.config.get('rows', '15')}),
            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: DCRM   Author: 82Flex   File: helper.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def render_layout(self, form, context, template_pack=TEMPLATE_PACK):
        """
        Copy any field label to the ``placeholder`` attribute.
        Note, this method is called when :attr:`layout` is defined.
        """
        # Writing the label values into the field placeholders.
        # This is done at rendering time, so the Form.__init__() could update any labels before.
        # Django 1.11 no longer lets EmailInput or URLInput inherit from TextInput,
        # so checking for `Input` instead while excluding `HiddenInput`.
        for field in form.fields.values():
            if field.label and \
                    isinstance(field.widget, (Input, forms.Textarea)) and \
                    not isinstance(field.widget, forms.HiddenInput):
                field.widget.attrs['placeholder'] = u"{0}:".format(field.label)

        return super(CompactLabelsCommentFormHelper, self).render_layout(form, context, template_pack=template_pack) 
Example 4
Project: starthinker   Author: google   File: forms_json.py    License: Apache License 2.0 6 votes vote down vote up
def get_field_kind(field):
  if field['kind'] == 'string':
    return forms.CharField(max_length=255, required=False)
  elif field['kind'] == 'email':
    return forms.EmailField(max_length=255, required=False)
  elif field['kind'] == 'integer':
    return forms.IntegerField(required=False)
  elif field['kind'] == 'boolean':
    return forms.BooleanField(required=False)
  elif field['kind'] == 'text':
    return forms.CharField(widget=forms.Textarea(), required=False)
  elif field['kind'] == 'choice':
    return forms.ChoiceField(choices=map(lambda c: (c,c), field['choices']))
  elif field['kind'] == 'timezones':
    return TimezoneField()
  elif field['kind'] == 'authentication':
    return SwitchField('user', 'service', required=True)
  elif field['kind'] == 'json':
    return JsonField(required=False)
  elif field['kind'] == 'integer_list':
    return CommaSeparatedIntegerField(required=False)
  elif field['kind'] == 'string_list':
    return CommaSeparatedCharField(required=False)
  else:
    return forms.CharField(max_length=255, required=False) 
Example 5
def test_explicit_formset_dict(self):
        class BandForm(ClusterForm):
            class Meta:
                model = Band
                formsets = {
                    'albums': {'fields': ['name'], 'widgets': {'name': Textarea()}}
                }
                fields = ['name']

        form = BandForm()
        self.assertTrue(form.formsets.get('albums'))
        self.assertFalse(form.formsets.get('members'))

        self.assertTrue('albums' in form.as_p())
        self.assertFalse('members' in form.as_p())

        self.assertIn('name', form.formsets['albums'].forms[0].fields)
        self.assertNotIn('release_date', form.formsets['albums'].forms[0].fields)
        self.assertEqual(Textarea, type(form.formsets['albums'].forms[0]['name'].field.widget)) 
Example 6
def test_formfield_callback(self):

        def formfield_for_dbfield(db_field, **kwargs):
            # a particularly stupid formfield_callback that just uses Textarea for everything
            return CharField(widget=Textarea, **kwargs)

        class BandFormWithFFC(ClusterForm):
            formfield_callback = formfield_for_dbfield

            class Meta:
                model = Band
                fields = ['name']

        form = BandFormWithFFC()
        self.assertEqual(Textarea, type(form['name'].field.widget))
        self.assertEqual(Textarea, type(form.formsets['members'].forms[0]['name'].field.widget)) 
Example 7
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 8
Project: wagtail   Author: wagtail   File: test_edit_handlers.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setUp(self):
        self.request = RequestFactory().get('/')
        user = AnonymousUser()  # technically, Anonymous users cannot access the admin
        self.request.user = user

        # a custom tabbed interface for EventPage
        self.event_page_tabbed_interface = TabbedInterface([
            ObjectList([
                FieldPanel('title', widget=forms.Textarea),
                FieldPanel('date_from'),
                FieldPanel('date_to'),
            ], heading='Event details', classname="shiny"),
            ObjectList([
                InlinePanel('speakers', label="Speakers"),
            ], heading='Speakers'),
        ]).bind_to(model=EventPage, request=self.request) 
Example 9
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 10
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_custom_callback(self):
        """A custom formfield_callback is used if provided"""
        callback_args = []

        def callback(db_field, **kwargs):
            callback_args.append((db_field, kwargs))
            return db_field.formfield(**kwargs)

        widget = forms.Textarea()

        class BaseForm(forms.ModelForm):
            class Meta:
                model = Person
                widgets = {'name': widget}
                fields = "__all__"

        modelform_factory(Person, form=BaseForm, formfield_callback=callback)
        id_field, name_field = Person._meta.fields

        self.assertEqual(callback_args, [(id_field, {}), (name_field, {'widget': widget})]) 
Example 11
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_inherit_after_custom_callback(self):
        def callback(db_field, **kwargs):
            if isinstance(db_field, models.CharField):
                return forms.CharField(widget=forms.Textarea)
            return db_field.formfield(**kwargs)

        class BaseForm(forms.ModelForm):
            class Meta:
                model = Person
                fields = '__all__'

        NewForm = modelform_factory(Person, form=BaseForm, formfield_callback=callback)

        class InheritedForm(NewForm):
            pass

        for name in NewForm.base_fields:
            self.assertEqual(
                type(InheritedForm.base_fields[name].widget),
                type(NewForm.base_fields[name].widget)
            ) 
Example 12
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_custom_callback(self):
        """A custom formfield_callback is used if provided"""
        callback_args = []

        def callback(db_field, **kwargs):
            callback_args.append((db_field, kwargs))
            return db_field.formfield(**kwargs)

        widget = forms.Textarea()

        class BaseForm(forms.ModelForm):
            class Meta:
                model = Person
                widgets = {'name': widget}
                fields = "__all__"

        modelform_factory(Person, form=BaseForm, formfield_callback=callback)
        id_field, name_field = Person._meta.fields

        self.assertEqual(callback_args, [(id_field, {}), (name_field, {'widget': widget})]) 
Example 13
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_inherit_after_custom_callback(self):
        def callback(db_field, **kwargs):
            if isinstance(db_field, models.CharField):
                return forms.CharField(widget=forms.Textarea)
            return db_field.formfield(**kwargs)

        class BaseForm(forms.ModelForm):
            class Meta:
                model = Person
                fields = '__all__'

        NewForm = modelform_factory(Person, form=BaseForm, formfield_callback=callback)

        class InheritedForm(NewForm):
            pass

        for name in NewForm.base_fields:
            self.assertEqual(
                type(InheritedForm.base_fields[name].widget),
                type(NewForm.base_fields[name].widget)
            ) 
Example 14
Project: donation-tracker   Author: GamesDoneQuick   File: forms.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, event=None, *args, **kwargs):
        super(DonationEntryForm, self).__init__(*args, **kwargs)
        minDonationAmount = (
            event.minimumdonation if event is not None else Decimal('1.00')
        )
        self.fields['amount'] = forms.DecimalField(
            decimal_places=2,
            min_value=minDonationAmount,
            max_value=Decimal('100000'),
            label='Donation Amount (min ${0})'.format(minDonationAmount),
            widget=tracker.widgets.NumberInput(
                attrs={
                    'id': 'iDonationAmount',
                    'min': str(minDonationAmount),
                    'step': '0.01',
                }
            ),
            required=True,
        )
        self.fields['comment'] = forms.CharField(widget=forms.Textarea, required=False)
        self.fields['requestedvisibility'] = forms.ChoiceField(
            initial='CURR',
            choices=models.Donation._meta.get_field('requestedvisibility').choices,
            label='Name Visibility',
        )
        self.fields['requestedalias'] = forms.CharField(
            max_length=32, label='Preferred Alias', required=False
        )
        self.fields['requestedemail'] = forms.EmailField(
            max_length=128, label='Preferred Email', required=False
        )
        self.fields['requestedsolicitemail'] = forms.ChoiceField(
            initial='CURR',
            choices=models.Donation._meta.get_field('requestedsolicitemail').choices,
            label='Charity Email Opt In',
        ) 
Example 15
Project: donation-tracker   Author: GamesDoneQuick   File: forms.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(PrizeAcceptanceForm, self).__init__(*args, **kwargs)
        self.accepted = None

        if 'data' in kwargs and kwargs['data'] is not None:
            if 'accept' in kwargs['data']:
                self.accepted = True
            elif 'deny' in kwargs['data']:
                self.accepted = False

        self.fields['count'] = forms.ChoiceField(
            initial=self.instance.pendingcount,
            choices=list([(x, x) for x in range(1, self.instance.pendingcount + 1)]),
            label='Count',
            help_text='You were selected to win more than one copy of this prize, please select how many you would like to take, or press Deny All if you do not want any of them.',
        )
        if self.instance.pendingcount == 1:
            self.fields['count'].widget = forms.HiddenInput()
        self.fields['total'] = forms.IntegerField(
            initial=self.instance.pendingcount,
            validators=[positive],
            widget=forms.HiddenInput(),
        )
        self.fields['comments'] = forms.CharField(
            max_length=512,
            label='Notes',
            required=False,
            help_text='Please put any additional notes here (such as if you have the option of customizing your prize before it is shipped, or additional delivery information).',
            widget=forms.Textarea(attrs=dict(cols=40, rows=2)),
        ) 
Example 16
Project: donation-tracker   Author: GamesDoneQuick   File: forms.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(PrizeShippingForm, self).__init__(*args, **kwargs)
        self.saved = False
        self.instance = kwargs['instance']
        self.fields['shippingstate'].label = (
            'Shipped yet?' if self.instance.prize.requiresshipping else 'Sent yet?'
        )
        self.fields[
            'shippingcost'
        ].help_text = 'Fill in the amount you would like to be reimbursed for (leave blank for zero)'
        self.fields[
            'shipping_receipt_url'
        ].help_text = 'Please post a url with an image of the shipping receipt here. If you are uncomfortable uploading this image to a web page, you can send the image to {0} instead'.format(
            prizemail.get_event_default_sender_email(self.instance.prize.event)
        )
        self.fields[
            'couriername'
        ].help_text = '(e.g. FedEx, DHL, ...) Optional, but nice if you have it'
        self.fields[
            'trackingnumber'
        ].help_text = 'Optional, and you must also supply the courier name if you want to provide a tracking number'
        self.fields['shippingnotes'].label = 'Additional Notes'
        self.fields[
            'shippingnotes'
        ].help_text = 'Any extra information you would like to relay to the recipient'
        self.fields['shippingnotes'].widget = forms.Textarea(
            attrs=dict(cols=40, rows=2)
        )
        if not self.instance.prize.requiresshipping:
            self.fields['shippingcost'].widget = forms.HiddenInput()
            self.fields['shipping_receipt_url'].widget = forms.HiddenInput()
            self.fields['couriername'].widget = forms.HiddenInput()
            self.fields['trackingnumber'].widget = forms.HiddenInput() 
Example 17
Project: coursys   Author: sfu-fas   File: text.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_entry_field(self, questionanswer=None, student=None):
        max_length = self.version.config.get('max_length', 10000)
        lines = self.version.config.get('lines', 5)
        if questionanswer:
            initial = questionanswer.answer.get('data', '')
        else:
            initial = None

        field = forms.CharField(required=False, max_length=max_length, initial=initial,
                                widget=forms.Textarea(attrs={'rows': lines, 'cols': 100}))
        field.widget.attrs.update({'class': 'long-answer'})
        return field 
Example 18
Project: coursys   Author: sfu-fas   File: gittag.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
            super(GitTag.ComponentForm, self).__init__(*args, **kwargs)
            self.fields.__delitem__('specified_filename')
            self.fields['description'].widget = forms.Textarea(attrs={'cols': 50, 'rows': 5}) 
Example 19
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.Textarea(attrs={'cols': 70, 'rows': 20})
        if 'help_text' not in kwargs:
            kwargs['help_text'] = 'Page formatted in <a href="/docs/pages">WikiCreole markup</a>.' # hard-coded URL since this is evaluated before urls.py: could be reverse_lazy?
        super(WikiField, self).__init__(*args, **kwargs) 
Example 20
Project: coursys   Author: sfu-fas   File: markup.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        widgets = (
            forms.Textarea(attrs={'cols': 70, 'rows': 20}),
            forms.Select(),
            forms.CheckboxInput(),
        )
        super(MarkupContentWidget, self).__init__(widgets) 
Example 21
Project: coursys   Author: sfu-fas   File: forms.py    License: GNU General Public License v3.0 5 votes vote down vote up
def add_extra_questions(self, posting):
        if 'extra_questions' in posting.config and len(posting.config['extra_questions']) > 0:
            for question in posting.config['extra_questions']:
                if 'extra_questions' in self.instance.config and question in self.instance.config['extra_questions']:
                    self.fields[question] = forms.CharField(label="Question", help_text=question, widget=forms.Textarea, initial=self.instance.config['extra_questions'][question])
                else:
                    self.fields[question] = forms.CharField(label="Question", help_text=question, widget=forms.Textarea) 
Example 22
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def formfield(self, **kwargs):
        # Passing max_length to forms.CharField means that the value's length
        # will be validated twice. This is considered acceptable since we want
        # the value in the form field (to pass into widget for example).
        defaults = {'max_length': self.max_length, 'widget': forms.Textarea}
        defaults.update(kwargs)
        return super(TextField, self).formfield(**defaults) 
Example 23
Project: bioforum   Author: reBiocoder   File: __init__.py    License: MIT License 5 votes vote down vote up
def formfield(self, **kwargs):
        # Passing max_length to forms.CharField means that the value's length
        # will be validated twice. This is considered acceptable since we want
        # the value in the form field (to pass into widget for example).
        defaults = {'max_length': self.max_length}
        if not self.choices:
            defaults['widget'] = forms.Textarea
        defaults.update(kwargs)
        return super().formfield(**defaults) 
Example 24
Project: django-bleach   Author: marksweb   File: forms.py    License: MIT License 5 votes vote down vote up
def get_default_widget():
    """ Get the default widget or the widget defined in settings """
    default_widget = forms.Textarea
    if hasattr(settings, 'BLEACH_DEFAULT_WIDGET'):
        default_widget = load_widget(settings.BLEACH_DEFAULT_WIDGET)
    return default_widget 
Example 25
Project: django-bleach   Author: marksweb   File: test_settings.py    License: MIT License 5 votes vote down vote up
def test_default_widget(self):
        self.assertEqual(get_default_widget(), Textarea) 
Example 26
Project: tom_base   Author: TOMToolkit   File: forms.py    License: GNU General Public License v3.0 5 votes vote down vote up
def extra_field_to_form_field(field_type):
    if field_type == 'number':
        return forms.FloatField(required=False)
    elif field_type == 'boolean':
        return forms.BooleanField(required=False)
    elif field_type == 'datetime':
        return forms.DateTimeField(required=False)
    elif field_type == 'string':
        return forms.CharField(required=False, widget=forms.Textarea)
    else:
        raise ValueError(
            'Invalid field type {}. Field type must be one of: number, boolean, datetime string'.format(field_type)
        ) 
Example 27
Project: rdmo   Author: rdmorganiser   File: forms.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)

        self.fields['first_name'].widget = forms.TextInput(attrs={'placeholder': _('First name')})
        self.fields['last_name'].widget = forms.TextInput(attrs={'placeholder': _('Last name')})

        self.additional_fields = AdditionalField.objects.all()
        self.additional_values = self.instance.additional_values.all()

        # add fields and init values for the Profile model
        for additional_field in self.additional_fields:

            if additional_field.type == 'text':
                field = forms.CharField(widget=forms.TextInput(attrs={'placeholder': additional_field.text}))
            elif additional_field.type == 'textarea':
                field = forms.CharField(widget=forms.Textarea(attrs={'placeholder': additional_field.text}))
            else:
                raise Exception('Unknown additional_field type.')

            field.label = additional_field.text
            field.help = additional_field.help
            field.required = additional_field.required

            self.fields[additional_field.key] = field

        for additional_field_value in self.additional_values:
            self.fields[additional_field.key].initial = additional_field_value.value 
Example 28
Project: clist   Author: aropan   File: admin.py    License: Apache License 2.0 5 votes vote down vote up
def formfield_for_dbfield(self, db_field, **kwargs):
        formfield = super().formfield_for_dbfield(db_field, **kwargs)
        if isinstance(db_field, models.fields.CharField) and db_field.name in getattr(self, 'textarea_fields', []):
            formfield.widget = forms.Textarea(attrs=formfield.widget.attrs)
        return formfield 
Example 29
def test_widget_overrides(self):
        class BandForm(ClusterForm):
            class Meta:
                model = Band
                widgets = {
                    'name': Textarea(),
                    'members': {
                        'name': Textarea()
                    }
                }
                fields = ['name']

        form = BandForm()
        self.assertEqual(Textarea, type(form['name'].field.widget))
        self.assertEqual(Textarea, type(form.formsets['members'].forms[0]['name'].field.widget)) 
Example 30
Project: django-rdkit   Author: rdkit   File: fields.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def formfield(self, **kwargs):
        # Use TextField as default input form to accommodate line breaks needed for molBlocks
        defaults = {'form_class': forms.CharField, 'strip': False, 'widget':forms.Textarea}
        defaults.update(kwargs)
        return super().formfield(**defaults)

##########################################
# Reaction Field