Example #1
0
    def __init__(self, required=True, widget=None, label=None, initial=None, help_text=None):
        # required -- Boolean that specifies whether the field is required.
        #             True by default.
        # widget -- A Widget class, or instance of a Widget class, that should be
        #         used for this Field when displaying it. Each Field has a default
        #         Widget that it'll use if you don't specify this. In most cases,
        #         the default widget is TextInput.
        # label -- A verbose name for this field, for use in displaying this field in
        #         a form. By default, Django will use a "pretty" version of the form
        #         field name, if the Field is part of a Form.
        # initial -- A value to use in this Field's initial display. This value is
        #            *not* used as a fallback if data isn't given.
        # help_text -- An optional string to use as "help text" for this Field.
        if label is not None:
            label = smart_unicode(label)
        self.required, self.label, self.initial = required, label, initial
        self.help_text = smart_unicode(help_text or '')
        widget = widget or self.widget
        if isinstance(widget, type):
            widget = widget()

        # Hook into self.widget_attrs() for any Field-specific HTML attributes.
        extra_attrs = self.widget_attrs(widget)
        if extra_attrs:
            widget.attrs.update(extra_attrs)

        self.widget = widget

        # Increase the creation counter, and save our local copy.
        self.creation_counter = Field.creation_counter
        Field.creation_counter += 1
 def render(self, name, value, attrs=None, choices=()):
     if value is None: value = ''
     final_attrs = self.build_attrs(attrs, name=name)
     output = [u'<select%s>' % flatatt(final_attrs)]
     str_value = smart_unicode(value)  # Normalize to string.
     for option_value, option_label in chain(self.choices, choices):
         option_value = smart_unicode(option_value)
         selected_html = (option_value
                          == str_value) and u' selected="selected"' or ''
         output.append(u'<option value="%s"%s>%s</option>' %
                       (escape(option_value), selected_html,
                        escape(smart_unicode(option_label))))
     output.append(u'</select>')
     return u'\n'.join(output)
Example #3
0
 def render(self, name, value, attrs=None, choices=()):
     if value is None:
         value = []
     final_attrs = self.build_attrs(attrs, name=name)
     output = [u'<select multiple="multiple"%s>' % flatatt(final_attrs)]
     str_values = set([smart_unicode(v) for v in value])  # Normalize to strings.
     for option_value, option_label in chain(self.choices, choices):
         option_value = smart_unicode(option_value)
         selected_html = (option_value in str_values) and ' selected="selected"' or ""
         output.append(
             u'<option value="%s"%s>%s</option>'
             % (escape(option_value), selected_html, escape(smart_unicode(option_label)))
         )
     output.append(u"</select>")
     return u"\n".join(output)
 def render(self, name, value, attrs=None, choices=()):
     "Returns a RadioFieldRenderer instance rather than a Unicode string."
     if value is None: value = ''
     str_value = smart_unicode(value)  # Normalize to string.
     attrs = attrs or {}
     return RadioFieldRenderer(name, str_value, attrs,
                               list(chain(self.choices, choices)))
Example #5
0
 def render(self, name, value, attrs=None):
     if value is None:
         value = ""
     final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
     if value != "":
         final_attrs["value"] = smart_unicode(value)  # Only add the 'value' attribute if a value is non-empty.
     return u"<input%s />" % flatatt(final_attrs)
Example #6
0
 def render(self, name, value, attrs=None, choices=()):
     "Returns a RadioFieldRenderer instance rather than a Unicode string."
     if value is None:
         value = ""
     str_value = smart_unicode(value)  # Normalize to string.
     attrs = attrs or {}
     return RadioFieldRenderer(name, str_value, attrs, list(chain(self.choices, choices)))
 def render(self, name, value, attrs=None):
     if value is None: value = ''
     final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
     if value != '':
         final_attrs['value'] = smart_unicode(
             value
         )  # Only add the 'value' attribute if a value is non-empty.
     return u'<input%s />' % flatatt(final_attrs)
 def render(self, name, value, attrs=None, choices=()):
     if value is None: value = []
     final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
     return u'\n'.join([
         (u'<input%s />' %
          flatatt(dict(value=smart_unicode(v), **final_attrs)))
         for v in value
     ])
Example #9
0
 def render(self, name, value, attrs=None, choices=()):
     if value is None:
         value = []
     has_id = attrs and attrs.has_key("id")
     final_attrs = self.build_attrs(attrs, name=name)
     output = [u"<ul>"]
     str_values = set([smart_unicode(v) for v in value])  # Normalize to strings.
     for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
         # If an ID attribute was given, add a numeric index as a suffix,
         # so that the checkboxes don't all have the same ID attribute.
         if has_id:
             final_attrs = dict(final_attrs, id="%s_%s" % (attrs["id"], i))
         cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values)
         option_value = smart_unicode(option_value)
         rendered_cb = cb.render(name, option_value)
         output.append(u"<li><label>%s %s</label></li>" % (rendered_cb, escape(smart_unicode(option_label))))
     output.append(u"</ul>")
     return u"\n".join(output)
Example #10
0
 def clean(self, value):
     "Validates max_length and min_length. Returns a Unicode object."
     super(CharField, self).clean(value)
     if value in EMPTY_VALUES:
         return u''
     value = smart_unicode(value)
     if self.max_length is not None and len(value) > self.max_length:
         raise ValidationError(gettext(u'Ensure this value has at most %d characters.') % self.max_length)
     if self.min_length is not None and len(value) < self.min_length:
         raise ValidationError(gettext(u'Ensure this value has at least %d characters.') % self.min_length)
     return value
Example #11
0
 def render(self, name, value, attrs=None):
     final_attrs = self.build_attrs(attrs, type="checkbox", name=name)
     try:
         result = self.check_test(value)
     except:  # Silently catch exceptions
         result = False
     if result:
         final_attrs["checked"] = "checked"
     if value not in ("", True, False, None):
         final_attrs["value"] = smart_unicode(value)  # Only add the 'value' attribute if a value is non-empty.
     return u"<input%s />" % flatatt(final_attrs)
Example #12
0
 def clean(self, value):
     """
     Validates that the input is a list or tuple.
     """
     if self.required and not value:
         raise ValidationError(gettext(u'This field is required.'))
     elif not self.required and not value:
         return []
     if not isinstance(value, (list, tuple)):
         raise ValidationError(gettext(u'Enter a list of values.'))
     new_value = []
     for val in value:
         val = smart_unicode(val)
         new_value.append(val)
     # Validate that each value in the value list is in self.choices.
     valid_values = set([smart_unicode(k) for k, v in self.choices])
     for val in new_value:
         if val not in valid_values:
             raise ValidationError(gettext(u'Select a valid choice. %s is not one of the available choices.') % val)
     return new_value
 def render(self, name, value, attrs=None, choices=()):
     if value is None: value = []
     has_id = attrs and attrs.has_key('id')
     final_attrs = self.build_attrs(attrs, name=name)
     output = [u'<ul>']
     str_values = set([smart_unicode(v)
                       for v in value])  # Normalize to strings.
     for i, (option_value,
             option_label) in enumerate(chain(self.choices, choices)):
         # If an ID attribute was given, add a numeric index as a suffix,
         # so that the checkboxes don't all have the same ID attribute.
         if has_id:
             final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
         cb = CheckboxInput(final_attrs,
                            check_test=lambda value: value in str_values)
         option_value = smart_unicode(option_value)
         rendered_cb = cb.render(name, option_value)
         output.append(u'<li><label>%s %s</label></li>' %
                       (rendered_cb, escape(smart_unicode(option_label))))
     output.append(u'</ul>')
     return u'\n'.join(output)
 def render(self, name, value, attrs=None):
     final_attrs = self.build_attrs(attrs, type='checkbox', name=name)
     try:
         result = self.check_test(value)
     except:  # Silently catch exceptions
         result = False
     if result:
         final_attrs['checked'] = 'checked'
     if value not in ('', True, False, None):
         final_attrs['value'] = smart_unicode(
             value
         )  # Only add the 'value' attribute if a value is non-empty.
     return u'<input%s />' % flatatt(final_attrs)
Example #15
0
 def clean(self, value):
     """
     Validates that the input is in self.choices.
     """
     value = super(ChoiceField, self).clean(value)
     if value in EMPTY_VALUES:
         value = u''
     value = smart_unicode(value)
     if value == u'':
         return value
     valid_values = set([str(k) for k, v in self.choices])
     if value not in valid_values:
         raise ValidationError(gettext(u'Select a valid choice. That choice is not one of the available choices.'))
     return value
Example #16
0
 def clean(self, value):
     """
     Validates that the input is a list or tuple.
     """
     if self.required and not value:
         raise ValidationError(gettext(u'This field is required.'))
     elif not self.required and not value:
         return []
     if not isinstance(value, (list, tuple)):
         raise ValidationError(gettext(u'Enter a list of values.'))
     new_value = []
     for val in value:
         val = smart_unicode(val)
         new_value.append(val)
     # Validate that each value in the value list is in self.choices.
     valid_values = set([smart_unicode(k) for k, v in self.choices])
     for val in new_value:
         if val not in valid_values:
             raise ValidationError(
                 gettext(
                     u'Select a valid choice. %s is not one of the available choices.'
                 ) % val)
     return new_value
Example #17
0
    def __init__(self,
                 required=True,
                 widget=None,
                 label=None,
                 initial=None,
                 help_text=None):
        # required -- Boolean that specifies whether the field is required.
        #             True by default.
        # widget -- A Widget class, or instance of a Widget class, that should be
        #         used for this Field when displaying it. Each Field has a default
        #         Widget that it'll use if you don't specify this. In most cases,
        #         the default widget is TextInput.
        # label -- A verbose name for this field, for use in displaying this field in
        #         a form. By default, Django will use a "pretty" version of the form
        #         field name, if the Field is part of a Form.
        # initial -- A value to use in this Field's initial display. This value is
        #            *not* used as a fallback if data isn't given.
        # help_text -- An optional string to use as "help text" for this Field.
        if label is not None:
            label = smart_unicode(label)
        self.required, self.label, self.initial = required, label, initial
        self.help_text = smart_unicode(help_text or '')
        widget = widget or self.widget
        if isinstance(widget, type):
            widget = widget()

        # Hook into self.widget_attrs() for any Field-specific HTML attributes.
        extra_attrs = self.widget_attrs(widget)
        if extra_attrs:
            widget.attrs.update(extra_attrs)

        self.widget = widget

        # Increase the creation counter, and save our local copy.
        self.creation_counter = Field.creation_counter
        Field.creation_counter += 1
Example #18
0
 def clean(self, value):
     "Validates max_length and min_length. Returns a Unicode object."
     super(CharField, self).clean(value)
     if value in EMPTY_VALUES:
         return u''
     value = smart_unicode(value)
     if self.max_length is not None and len(value) > self.max_length:
         raise ValidationError(
             gettext(u'Ensure this value has at most %d characters.') %
             self.max_length)
     if self.min_length is not None and len(value) < self.min_length:
         raise ValidationError(
             gettext(u'Ensure this value has at least %d characters.') %
             self.min_length)
     return value
Example #19
0
 def clean(self, value):
     """
     Validates that the input is in self.choices.
     """
     value = super(ChoiceField, self).clean(value)
     if value in EMPTY_VALUES:
         value = u''
     value = smart_unicode(value)
     if value == u'':
         return value
     valid_values = set([str(k) for k, v in self.choices])
     if value not in valid_values:
         raise ValidationError(
             gettext(
                 u'Select a valid choice. That choice is not one of the available choices.'
             ))
     return value
Example #20
0
 def clean(self, value):
     """
     Validates that the input matches the regular expression. Returns a
     Unicode object.
     """
     super(RegexField, self).clean(value)
     if value in EMPTY_VALUES:
         value = u''
     value = smart_unicode(value)
     if value == u'':
         return value
     if self.max_length is not None and len(value) > self.max_length:
         raise ValidationError(gettext(u'Ensure this value has at most %d characters.') % self.max_length)
     if self.min_length is not None and len(value) < self.min_length:
         raise ValidationError(gettext(u'Ensure this value has at least %d characters.') % self.min_length)
     if not self.regex.search(value):
         raise ValidationError(self.error_message)
     return value
Example #21
0
 def clean(self, value):
     """
     Validates that the input matches the regular expression. Returns a
     Unicode object.
     """
     super(RegexField, self).clean(value)
     if value in EMPTY_VALUES:
         value = u''
     value = smart_unicode(value)
     if value == u'':
         return value
     if self.max_length is not None and len(value) > self.max_length:
         raise ValidationError(
             gettext(u'Ensure this value has at most %d characters.') %
             self.max_length)
     if self.min_length is not None and len(value) < self.min_length:
         raise ValidationError(
             gettext(u'Ensure this value has at least %d characters.') %
             self.min_length)
     if not self.regex.search(value):
         raise ValidationError(self.error_message)
     return value
Example #22
0
 def render(self, name, value, attrs=None, choices=()):
     if value is None:
         value = []
     final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
     return u"\n".join([(u"<input%s />" % flatatt(dict(value=smart_unicode(v), **final_attrs))) for v in value])
 def render(self, name, value, attrs=None):
     if value is None: value = ''
     value = smart_unicode(value)
     final_attrs = self.build_attrs(attrs, name=name)
     return u'<textarea%s>%s</textarea>' % (flatatt(final_attrs),
                                            escape(value))
 def __init__(self, name, value, attrs, choice, index):
     self.name, self.value = name, value
     self.attrs = attrs
     self.choice_value = smart_unicode(choice[0])
     self.choice_label = smart_unicode(choice[1])
     self.index = index
Example #25
0
 def render(self, name, value, attrs=None):
     if value is None:
         value = ""
     value = smart_unicode(value)
     final_attrs = self.build_attrs(attrs, name=name)
     return u"<textarea%s>%s</textarea>" % (flatatt(final_attrs), escape(value))
Example #26
0
 def __init__(self, name, value, attrs, choice, index):
     self.name, self.value = name, value
     self.attrs = attrs
     self.choice_value = smart_unicode(choice[0])
     self.choice_label = smart_unicode(choice[1])
     self.index = index