From 46786b4193e04d398532bbfc3dcf63c03c1793cb Mon Sep 17 00:00:00 2001 From: Jacob Kaplan-Moss Date: Sat, 19 Jul 2008 01:22:26 +0000 Subject: Fixed #7741: django.newforms is now django.forms. This is obviously a backwards-incompatible change. There's a warning upon import of django.newforms itself, but deeper imports will raise errors. git-svn-id: http://code.djangoproject.com/svn/django/trunk@7971 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/newforms/__init__.py | 25 +- django/newforms/extras/__init__.py | 1 - django/newforms/extras/widgets.py | 79 ---- django/newforms/fields.py | 812 ------------------------------------- django/newforms/forms.py | 396 ------------------ django/newforms/formsets.py | 292 ------------- django/newforms/models.py | 608 --------------------------- django/newforms/util.py | 69 ---- django/newforms/widgets.py | 647 ----------------------------- 9 files changed, 7 insertions(+), 2922 deletions(-) delete mode 100644 django/newforms/extras/__init__.py delete mode 100644 django/newforms/extras/widgets.py delete mode 100644 django/newforms/fields.py delete mode 100644 django/newforms/forms.py delete mode 100644 django/newforms/formsets.py delete mode 100644 django/newforms/models.py delete mode 100644 django/newforms/util.py delete mode 100644 django/newforms/widgets.py (limited to 'django/newforms') diff --git a/django/newforms/__init__.py b/django/newforms/__init__.py index 99631e4e8f..5f319f8c1b 100644 --- a/django/newforms/__init__.py +++ b/django/newforms/__init__.py @@ -1,18 +1,7 @@ -""" -Django validation and HTML form handling. - -TODO: - Default value for field - Field labels - Nestable Forms - FatalValidationError -- short-circuits all other validators on a form - ValidationWarning - "This form field requires foo.js" and form.js_includes() -""" - -from util import ValidationError -from widgets import * -from fields import * -from forms import * -from models import * -from formsets import * \ No newline at end of file +import warnings +warnings.warn( + category = DeprecationWarning, + message = "django.newforms is no longer new. Import django.forms instead.", + stacklevel = 2 +) +from django.forms import * \ No newline at end of file diff --git a/django/newforms/extras/__init__.py b/django/newforms/extras/__init__.py deleted file mode 100644 index a7f6a9b3f6..0000000000 --- a/django/newforms/extras/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from widgets import * diff --git a/django/newforms/extras/widgets.py b/django/newforms/extras/widgets.py deleted file mode 100644 index e3ef1d7f69..0000000000 --- a/django/newforms/extras/widgets.py +++ /dev/null @@ -1,79 +0,0 @@ -""" -Extra HTML Widget classes -""" - -import datetime -import re - -from django.newforms.widgets import Widget, Select -from django.utils.dates import MONTHS -from django.utils.safestring import mark_safe - -__all__ = ('SelectDateWidget',) - -RE_DATE = re.compile(r'(\d{4})-(\d\d?)-(\d\d?)$') - -class SelectDateWidget(Widget): - """ - A Widget that splits date input into three . - """ - return self.as_widget(TextInput(), attrs) - - def as_textarea(self, attrs=None): - "Returns a string of HTML for representing this as a ' % (flatatt(final_attrs), - conditional_escape(force_unicode(value)))) - -class DateTimeInput(Input): - input_type = 'text' - format = '%Y-%m-%d %H:%M:%S' # '2006-10-25 14:30:59' - - def __init__(self, attrs=None, format=None): - super(DateTimeInput, self).__init__(attrs) - if format: - self.format = format - - def render(self, name, value, attrs=None): - if value is None: - value = '' - elif hasattr(value, 'strftime'): - value = datetime_safe.new_datetime(value) - value = value.strftime(self.format) - return super(DateTimeInput, self).render(name, value, attrs) - -class CheckboxInput(Widget): - def __init__(self, attrs=None, check_test=bool): - super(CheckboxInput, self).__init__(attrs) - # check_test is a callable that takes a value and returns True - # if the checkbox should be checked for that value. - self.check_test = check_test - - 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): - # Only add the 'value' attribute if a value is non-empty. - final_attrs['value'] = force_unicode(value) - return mark_safe(u'' % flatatt(final_attrs)) - - def value_from_datadict(self, data, files, name): - if name not in data: - # A missing value means False because HTML form submission does not - # send results for unselected checkboxes. - return False - return super(CheckboxInput, self).value_from_datadict(data, files, name) - - def _has_changed(self, initial, data): - # Sometimes data or initial could be None or u'' which should be the - # same thing as False. - return bool(initial) != bool(data) - -class Select(Widget): - def __init__(self, attrs=None, choices=()): - super(Select, self).__init__(attrs) - # choices can be any iterable, but we may need to render this widget - # multiple times. Thus, collapse it into a list so it can be consumed - # more than once. - self.choices = list(choices) - - def render(self, name, value, attrs=None, choices=()): - if value is None: value = '' - final_attrs = self.build_attrs(attrs, name=name) - output = [u'' % flatatt(final_attrs)] - # Normalize to string. - str_value = force_unicode(value) - for option_value, option_label in chain(self.choices, choices): - option_value = force_unicode(option_value) - selected_html = (option_value == str_value) and u' selected="selected"' or '' - output.append(u'' % ( - escape(option_value), selected_html, - conditional_escape(force_unicode(option_label)))) - output.append(u'') - return mark_safe(u'\n'.join(output)) - -class NullBooleanSelect(Select): - """ - A Select Widget intended to be used with NullBooleanField. - """ - def __init__(self, attrs=None): - choices = ((u'1', ugettext('Unknown')), (u'2', ugettext('Yes')), (u'3', ugettext('No'))) - super(NullBooleanSelect, self).__init__(attrs, choices) - - def render(self, name, value, attrs=None, choices=()): - try: - value = {True: u'2', False: u'3', u'2': u'2', u'3': u'3'}[value] - except KeyError: - value = u'1' - return super(NullBooleanSelect, self).render(name, value, attrs, choices) - - def value_from_datadict(self, data, files, name): - value = data.get(name, None) - return {u'2': True, u'3': False, True: True, False: False}.get(value, None) - - def _has_changed(self, initial, data): - # Sometimes data or initial could be None or u'' which should be the - # same thing as False. - return bool(initial) != bool(data) - -class SelectMultiple(Widget): - def __init__(self, attrs=None, choices=()): - super(SelectMultiple, self).__init__(attrs) - # choices can be any iterable - self.choices = choices - - def render(self, name, value, attrs=None, choices=()): - if value is None: value = [] - final_attrs = self.build_attrs(attrs, name=name) - output = [u'') - return mark_safe(u'\n'.join(output)) - - def value_from_datadict(self, data, files, name): - if isinstance(data, MultiValueDict): - return data.getlist(name) - return data.get(name, None) - - def _has_changed(self, initial, data): - if initial is None: - initial = [] - if data is None: - data = [] - if len(initial) != len(data): - return True - for value1, value2 in zip(initial, data): - if force_unicode(value1) != force_unicode(value2): - return True - return False - -class RadioInput(StrAndUnicode): - """ - An object used by RadioFieldRenderer that represents a single - . - """ - - def __init__(self, name, value, attrs, choice, index): - self.name, self.value = name, value - self.attrs = attrs - self.choice_value = force_unicode(choice[0]) - self.choice_label = force_unicode(choice[1]) - self.index = index - - def __unicode__(self): - if 'id' in self.attrs: - label_for = ' for="%s_%s"' % (self.attrs['id'], self.index) - else: - label_for = '' - choice_label = conditional_escape(force_unicode(self.choice_label)) - return mark_safe(u'%s %s' % (label_for, self.tag(), choice_label)) - - def is_checked(self): - return self.value == self.choice_value - - def tag(self): - if 'id' in self.attrs: - self.attrs['id'] = '%s_%s' % (self.attrs['id'], self.index) - final_attrs = dict(self.attrs, type='radio', name=self.name, value=self.choice_value) - if self.is_checked(): - final_attrs['checked'] = 'checked' - return mark_safe(u'' % flatatt(final_attrs)) - -class RadioFieldRenderer(StrAndUnicode): - """ - An object used by RadioSelect to enable customization of radio widgets. - """ - - def __init__(self, name, value, attrs, choices): - self.name, self.value, self.attrs = name, value, attrs - self.choices = choices - - def __iter__(self): - for i, choice in enumerate(self.choices): - yield RadioInput(self.name, self.value, self.attrs.copy(), choice, i) - - def __getitem__(self, idx): - choice = self.choices[idx] # Let the IndexError propogate - return RadioInput(self.name, self.value, self.attrs.copy(), choice, idx) - - def __unicode__(self): - return self.render() - - def render(self): - """Outputs a
    for this set of radio fields.""" - return mark_safe(u'
      \n%s\n
    ' % u'\n'.join([u'
  • %s
  • ' - % force_unicode(w) for w in self])) - -class RadioSelect(Select): - renderer = RadioFieldRenderer - - def __init__(self, *args, **kwargs): - # Override the default renderer if we were passed one. - renderer = kwargs.pop('renderer', None) - if renderer: - self.renderer = renderer - super(RadioSelect, self).__init__(*args, **kwargs) - - def get_renderer(self, name, value, attrs=None, choices=()): - """Returns an instance of the renderer.""" - if value is None: value = '' - str_value = force_unicode(value) # Normalize to string. - final_attrs = self.build_attrs(attrs) - choices = list(chain(self.choices, choices)) - return self.renderer(name, str_value, final_attrs, choices) - - def render(self, name, value, attrs=None, choices=()): - return self.get_renderer(name, value, attrs, choices).render() - - def id_for_label(self, id_): - # RadioSelect is represented by multiple fields, - # each of which has a distinct ID. The IDs are made distinct by a "_X" - # suffix, where X is the zero-based index of the radio field. Thus, - # the label for a RadioSelect should reference the first one ('_0'). - if id_: - id_ += '_0' - return id_ - id_for_label = classmethod(id_for_label) - -class CheckboxSelectMultiple(SelectMultiple): - def render(self, name, value, attrs=None, choices=()): - if value is None: value = [] - has_id = attrs and 'id' in attrs - final_attrs = self.build_attrs(attrs, name=name) - output = [u'
      '] - # Normalize to strings - str_values = set([force_unicode(v) for v in value]) - 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)) - label_for = u' for="%s"' % final_attrs['id'] - else: - label_for = '' - - cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values) - option_value = force_unicode(option_value) - rendered_cb = cb.render(name, option_value) - option_label = conditional_escape(force_unicode(option_label)) - output.append(u'
    • %s %s
    • ' % (label_for, rendered_cb, option_label)) - output.append(u'
    ') - return mark_safe(u'\n'.join(output)) - - def id_for_label(self, id_): - # See the comment for RadioSelect.id_for_label() - if id_: - id_ += '_0' - return id_ - id_for_label = classmethod(id_for_label) - -class MultiWidget(Widget): - """ - A widget that is composed of multiple widgets. - - Its render() method is different than other widgets', because it has to - figure out how to split a single value for display in multiple widgets. - The ``value`` argument can be one of two things: - - * A list. - * A normal value (e.g., a string) that has been "compressed" from - a list of values. - - In the second case -- i.e., if the value is NOT a list -- render() will - first "decompress" the value into a list before rendering it. It does so by - calling the decompress() method, which MultiWidget subclasses must - implement. This method takes a single "compressed" value and returns a - list. - - When render() does its HTML rendering, each value in the list is rendered - with the corresponding widget -- the first value is rendered in the first - widget, the second value is rendered in the second widget, etc. - - Subclasses may implement format_output(), which takes the list of rendered - widgets and returns a string of HTML that formats them any way you'd like. - - You'll probably want to use this class with MultiValueField. - """ - def __init__(self, widgets, attrs=None): - self.widgets = [isinstance(w, type) and w() or w for w in widgets] - super(MultiWidget, self).__init__(attrs) - - def render(self, name, value, attrs=None): - # value is a list of values, each corresponding to a widget - # in self.widgets. - if not isinstance(value, list): - value = self.decompress(value) - output = [] - final_attrs = self.build_attrs(attrs) - id_ = final_attrs.get('id', None) - for i, widget in enumerate(self.widgets): - try: - widget_value = value[i] - except IndexError: - widget_value = None - if id_: - final_attrs = dict(final_attrs, id='%s_%s' % (id_, i)) - output.append(widget.render(name + '_%s' % i, widget_value, final_attrs)) - return mark_safe(self.format_output(output)) - - def id_for_label(self, id_): - # See the comment for RadioSelect.id_for_label() - if id_: - id_ += '_0' - return id_ - id_for_label = classmethod(id_for_label) - - def value_from_datadict(self, data, files, name): - return [widget.value_from_datadict(data, files, name + '_%s' % i) for i, widget in enumerate(self.widgets)] - - def _has_changed(self, initial, data): - if initial is None: - initial = [u'' for x in range(0, len(data))] - else: - initial = self.decompress(initial) - for widget, initial, data in zip(self.widgets, initial, data): - if widget._has_changed(initial, data): - return True - return False - - def format_output(self, rendered_widgets): - """ - Given a list of rendered widgets (as strings), returns a Unicode string - representing the HTML for the whole lot. - - This hook allows you to format the HTML design of the widgets, if - needed. - """ - return u''.join(rendered_widgets) - - def decompress(self, value): - """ - Returns a list of decompressed values for the given compressed value. - The given value can be assumed to be valid, but not necessarily - non-empty. - """ - raise NotImplementedError('Subclasses must implement this method.') - - def _get_media(self): - "Media for a multiwidget is the combination of all media of the subwidgets" - media = Media() - for w in self.widgets: - media = media + w.media - return media - media = property(_get_media) - -class SplitDateTimeWidget(MultiWidget): - """ - A Widget that splits datetime input into two boxes. - """ - def __init__(self, attrs=None): - widgets = (TextInput(attrs=attrs), TextInput(attrs=attrs)) - super(SplitDateTimeWidget, self).__init__(widgets, attrs) - - def decompress(self, value): - if value: - return [value.date(), value.time().replace(microsecond=0)] - return [None, None] - -- cgit v1.3