我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.forms.Textarea()。
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)
def __init__(self, *args, **kwargs): self.page=kwargs.pop('page') super(QuestionForm, self).__init__(*args, **kwargs) for p in Question.objects.filter(page=self.page): if p.id ==2: self.fields['url_field'] = forms.URLField(initial="http://",required = True) self.fields['url_field'].label = p.question self.fields['url_field'].page = p.page else: self.fields['extra_field_{index}'.format(index=p.id)] = forms.CharField(widget=forms.Textarea,required = True) self.fields['extra_field_{index}'.format(index=p.id)].label = p.question self.fields['extra_field_{index}'.format(index=p.id)].page = p.page
def __init__(self, *args, **kwargs): super(PostModelForm, self).__init__(*args, **kwargs) self.fields["title"].widget = forms.Textarea() self.fields["title"].error_messages = { "max_length": "This title is too long.", "required": "The title field is required." } self.fields["slug"].error_messages = { "max_length": "This title is too long.", "required": "The slug field is required.", "unique": "The slug field must be unique." } for field in self.fields.values(): field.error_messages = { 'required': "You know, {fieldname} is required".format(fieldname=field.label), }
def is_textarea(field): """Check if instance of Textarea widget.""" return isinstance(field.field.widget, forms.Textarea)
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 test_inline_edit_mod_textarea(self): class TempTable(MyTable): name = tables.Column(get_name, verbose_name="Verbose Name", sortable=True, form_field=forms.CharField( widget=forms.Textarea(), required=False), form_field_attributes={'class': 'test'}, update_action=MyUpdateAction) class Meta(object): name = "my_table" columns = ('id', 'name', 'value', 'optional', 'status') self.table = TempTable(self.request, TEST_DATA_2) name_col = self.table.columns['name'] name_col.auto = "form_field" row = self.table.get_rows()[0] name_cell = row.cells['name'] name_cell.inline_edit_mod = True # Check if is cell is rendered correctly. name_cell_rendered = name_cell.render() resp = http.HttpResponse(name_cell_rendered) self.assertContains(resp, '<textarea class="test" cols="40" id="name__1" ' 'name="name__1" rows="10">\r\ncustom object_1' '</textarea>', count=1, html=True)
def __init__(self, **kwargs): kwargs.setdefault('widget', forms.Textarea) super(JSONField, self).__init__(**kwargs)
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)
def render(self, name, value, attrs=None): # adding simplemde-editor class to the Textarea tag. if 'class' in attrs: attrs['class'] += ' simplemde-editor' else: attrs.update({'class': 'simplemde-editor'}) widget = super(SimpleMdeWidget, self).render(name, value, attrs) widget_html = render_to_string('simplemde/widget.html', { 'widget': widget }) return widget_html
def is_textarea(field): return isinstance(field.field.widget, forms.Textarea)
def __init__(self, attrs=None, nplurals=1): widgets = [forms.Textarea(attrs=attrs) for i_ in xrange(nplurals)] super(MultiStringWidget, self).__init__(widgets, attrs)
def __init__(self, *args, **kwargs): super(SourceDetailsForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) self.fields['bibtex'] = forms.CharField( widget=forms.Textarea(attrs={'class': 'bibtex'})) self.fields['bibtex'].initial = instance.bibtex for field in self.fields: self.fields[field].widget.attrs['readonly'] = True # if instance: # value = getattr(instance, field) # if value in ['', None]: # del self.fields[field]
def __init__(self, *args, **kwargs): super(SourceEditForm, self).__init__(*args, **kwargs) self.empty_permitted = False for field in self.fields: if field not in ['year', 'pages', 'number', 'edition', 'part', 'volume', 'ENTRYTYPE']: self.fields[field].widget = forms.Textarea( attrs={'cols': 22, 'rows': 1}) self.fields['citation_text'].label = 'Citation Text (required)' self.fields['citation_text'].required = True self.fields['shorthand'].label = 'Shorthand (required)' self.fields['shorthand'].required = True
def __init__(self, *args, **kwargs): kwargs['required'] = False kwargs['widget'] = forms.Textarea() forms.CharField.__init__(self, *args, **kwargs)
def __init__(self): super(NotificationMethod, self).__init__() if settings.EMAIL_BACKEND: self.server_configured = True if 'djembe' in settings.INSTALLED_APPS: self.options['certificate'] = forms.CharField(required=False, widget=forms.Textarea(attrs={'cols': 60, 'rows': 15}), help_text=_('Encryption certificate in PEM format.'))
def __init__(self, *args, **kwargs): super(ProfileForm, self).__init__(*args, **kwargs) self['mugshot'].field.widget = forms.FileInput() self['description'].field.widget = forms.Textarea(attrs={'rows': 3})
def __init__(self, *args, **kwargs): nb_questions = kwargs.pop('nb_questions') super(StatementForm, self).__init__(*args, **kwargs) for i in range(1, nb_questions + 1): self.fields['statement_%s' % i] = forms.CharField( required=True, widget=forms.Textarea(attrs={'rows': '2', 'cols': '80'})) self.fields['statement_%s' % i].label = 'Q%i' % i
def textarea(cls, question): return forms.CharField( required=False, label=mark_safe(question.text), help_text=mark_safe(question.descriptive_text), widget=forms.Textarea, )
def __init__(self, *args, **kwargs): questions = kwargs.pop('questions') super(SurveyForm, self).__init__(*args, **kwargs) for question in questions: self.fields['{0}{1}'.format(self.question_prefix, question.pk)] = \ forms.CharField(label=question.text, widget=forms.Textarea(attrs={'class': 'form-control'}))
def test_fields(self): """ This tests that all fields were added to the form with the correct types """ form_class = self.fb.get_form_class() field_names = form_class.base_fields.keys() # All fields are present in form self.assertIn('your-name', field_names) self.assertIn('your-biography', field_names) self.assertIn('your-birthday', field_names) self.assertIn('your-birthtime', field_names) self.assertIn('your-email', field_names) self.assertIn('your-homepage', field_names) self.assertIn('your-favourite-number', field_names) self.assertIn('your-favourite-python-ides', field_names) self.assertIn('your-favourite-python-ide', field_names) self.assertIn('your-choices', field_names) self.assertIn('i-agree-to-the-terms-of-use', field_names) # All fields have proper type self.assertIsInstance(form_class.base_fields['your-name'], forms.CharField) self.assertIsInstance(form_class.base_fields['your-biography'], forms.CharField) self.assertIsInstance(form_class.base_fields['your-birthday'], forms.DateField) self.assertIsInstance(form_class.base_fields['your-birthtime'], forms.DateTimeField) self.assertIsInstance(form_class.base_fields['your-email'], forms.EmailField) self.assertIsInstance(form_class.base_fields['your-homepage'], forms.URLField) self.assertIsInstance(form_class.base_fields['your-favourite-number'], forms.DecimalField) self.assertIsInstance(form_class.base_fields['your-favourite-python-ides'], forms.ChoiceField) self.assertIsInstance(form_class.base_fields['your-favourite-python-ide'], forms.ChoiceField) self.assertIsInstance(form_class.base_fields['your-choices'], forms.MultipleChoiceField) self.assertIsInstance(form_class.base_fields['i-agree-to-the-terms-of-use'], forms.BooleanField) # Some fields have non-default widgets self.assertIsInstance(form_class.base_fields['your-biography'].widget, forms.Textarea) self.assertIsInstance(form_class.base_fields['your-favourite-python-ide'].widget, forms.RadioSelect) self.assertIsInstance(form_class.base_fields['your-choices'].widget, forms.CheckboxSelectMultiple)
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 __init__(self, *args, **kwargs): super(RefundForm, self).__init__(*args, **kwargs) this_invoice = kwargs.pop('instance',None) for item in this_invoice.invoiceitem_set.all(): initial = False if item.finalEventRegistration: initial = item.finalEventRegistration.cancelled item_max = item.total + item.taxes if this_invoice.buyerPaysSalesTax else item.total self.fields["item_cancelled_%s" % item.id] = forms.BooleanField( label=_('Cancelled'),required=False,initial=initial) self.fields['item_refundamount_%s' % item.id] = forms.FloatField( label=_('Refund Amount'),required=False,initial=(-1) * item.adjustments, min_value=0, max_value=item_max) self.fields['comments'] = forms.CharField( label=_('Explanation/Comments (optional)'),required=False, help_text=_('This information will be added to the comments on the invoice associated with this refund.'), widget=forms.Textarea(attrs={'placeholder': _('Enter explanation/comments...'), 'class': 'form-control'})) self.fields['id'] = forms.ModelChoiceField( required=True,queryset=Invoice.objects.filter(id=this_invoice.id),widget=forms.HiddenInput(),initial=this_invoice.id) self.fields['initial_refund_amount'] = forms.FloatField( required=True,initial=(-1) * this_invoice.adjustments,min_value=0,max_value=this_invoice.amountPaid + this_invoice.refunds,widget=forms.HiddenInput()) self.fields['total_refund_amount'] = forms.FloatField( required=True,initial=0,min_value=0,max_value=this_invoice.amountPaid + this_invoice.refunds,widget=forms.HiddenInput())
def __init__(self, *args, **kwargs): self.page=kwargs.pop('page') super(QuestionForm, self).__init__(*args, **kwargs) for p in Question.objects.filter(page=self.page): # generate extra fields in the number specified via extra_fields self.fields['extra_field_{index}'.format(index=p.id)] = forms.CharField(widget=forms.Textarea,required = True) self.fields['extra_field_{index}'.format(index=p.id)].label = p.question self.fields['extra_field_{index}'.format(index=p.id)].page = p.page
def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) # http://stackoverflow.com/questions/350799/how-does-django-know-the-order-to-render-form-fields self.fields.keyOrder = ['title', 'acronym', 'startdate', 'starttime', 'enddate', 'endtime', 'timezone', 'tags', 'city', 'country', 'address', 'exact', 'coordinates_field', 'description'] self.fields['startdate'].label = _(u'Start date') self.fields['enddate'].label = _(u'End date') self.fields['address'].widget = forms.Textarea() self.fields['starttime'].widget.attrs.update( {'class': 'timePicker', } ) self.fields['endtime'].widget.attrs.update( {'class': 'timePicker', } ) if kwargs.has_key('instance'): # not a new event # We use a custom field called 'coordinates' for # showing/editing/entering latitude and longitude stored in # Event.coordinates (which is a Point). # If Event.exact is false, the coordinates (if present) are # pointing to the center of the city and we don't display them. # Otherwise we populate 'coordinates' with the values of # Event.coordinates instance = kwargs['instance'] coordinates_value = u'' if instance.coordinates: coordinates_value += str( instance.coordinates.y ) + u', ' + \ str( instance.coordinates.x ) if coordinates_value: self.fields['coordinates_field'].initial = coordinates_value # we also populate start and end dates: self.fields['startdate'].initial = instance.startdate self.fields['enddate'].initial = instance.enddate self.fields['starttime'].widget.format = '%H:%M' self.fields['endtime'].widget.format = '%H:%M'
def __init__(self, *args, **kwargs): super(SimplifiedEventForm, self).__init__(*args, **kwargs) self.fields['title'].label = _(u'Title') #self.fields['title'].widget = forms.Textarea() self.fields['where'].label = _(u'Where') self.fields['when'].label = _(u'When') self.fields['when'].widget.attrs.update({'class':'datePicker',}) self.fields['tags'].label = _(u'Tags or Topics') #self.fields['where'].help_text = \ # _(u'Example: Malmöer Str. 6, Berlin, DE') #self.fields['when'].help_text = \ # _(u"Examples: '25 Oct 2006', '2010-02-27', " \ # "'2010-02-27 11:00', '2010-02-27 11:00-13:00'")
def __init__(self, *args, **kwargs): """ Standard initialization routine, but with an explicit definition of the typedField's width and height based on database info. """ super(MonkeyTyperForm, self).__init__(*args, **kwargs) self.fields['typedField'].widget = forms.Textarea(attrs={'cols': self.instance.dieImage.bitWidth+2, 'rows': self.instance.dieImage.bitHeight+2})
def get_form(self, request, obj=None, **kwargs): self.exclude = ['show_header', 'show_content', 'show_file', 'show_url', 'set_linebreaks', 'use_for_migrations'] if obj: if not obj.show_header: self.exclude.extend(['header']) if not obj.show_content: self.exclude.extend(['content']) if not obj.show_file: self.exclude.extend(['file']) if not obj.show_url: self.exclude.extend(['url']) form = super(BlockAdmin, self).get_form(request, obj=obj, **kwargs) if 'header' not in self.exclude: form.base_fields['header'].widget = \ forms.Textarea(attrs={'class': 'vTextField'}) if 'file' not in self.exclude: form.base_fields['file'].widget = FileWidget() return form
def __init__(self, is_test_source=False, *args, **kwargs): super().__init__(*args, **kwargs) if is_test_source: self.fields['code'] = forms.CharField(widget=forms.Textarea) else: self.fields['file'] = forms.FileField()
def get_admin_widget(self): return forms.Textarea()
def get_form_field(self, **kwargs): """Return a Django form field appropriate for a string property. This sets the widget default to forms.Textarea if the property's multiline attribute is set. """ defaults = {} if self.multiline: defaults['widget'] = forms.Textarea defaults.update(kwargs) return super(StringProperty, self).get_form_field(**defaults)
def get_form_field(self, **kwargs): """Return a Django form field appropriate for a text property. This sets the widget default to forms.Textarea. """ defaults = {'widget': forms.Textarea} defaults.update(kwargs) return super(TextProperty, self).get_form_field(**defaults)
def get_form_field(self, **kwargs): """Return a Django form field appropriate for a StringList property. This defaults to a Textarea widget with a blank initial value. """ defaults = {'widget': forms.Textarea, 'initial': ''} defaults.update(kwargs) return super(StringListProperty, self).get_form_field(**defaults)