mirror of
https://github.com/django/django.git
synced 2025-10-24 22:26:08 +00:00
Fixed #18269 -- Applied unicode_literals for Python 3 compatibility.
Thanks Vinay Sajip for the support of his django3 branch and Jannis Leidel for the review.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Extra HTML Widget classes
|
||||
"""
|
||||
from __future__ import unicode_literals
|
||||
|
||||
import datetime
|
||||
import re
|
||||
@@ -90,7 +91,7 @@ class SelectDateWidget(Widget):
|
||||
output.append(month_html)
|
||||
elif field == 'day':
|
||||
output.append(day_html)
|
||||
return mark_safe(u'\n'.join(output))
|
||||
return mark_safe('\n'.join(output))
|
||||
|
||||
def id_for_label(self, id_):
|
||||
first_select = None
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
Field classes.
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import copy
|
||||
import datetime
|
||||
@@ -20,7 +20,7 @@ from django.forms.widgets import (TextInput, PasswordInput, HiddenInput,
|
||||
NullBooleanSelect, SelectMultiple, DateInput, DateTimeInput, TimeInput,
|
||||
SplitDateTimeWidget, SplitHiddenDateTimeWidget, FILE_INPUT_CONTRADICTION)
|
||||
from django.utils import formats
|
||||
from django.utils.encoding import smart_unicode, smart_str, force_unicode
|
||||
from django.utils.encoding import smart_unicode, force_unicode
|
||||
from django.utils.ipv6 import clean_ipv6_address
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
|
||||
@@ -44,8 +44,8 @@ class Field(object):
|
||||
hidden_widget = HiddenInput # Default widget to use when rendering this as "hidden".
|
||||
default_validators = [] # Default set of validators
|
||||
default_error_messages = {
|
||||
'required': _(u'This field is required.'),
|
||||
'invalid': _(u'Enter a valid value.'),
|
||||
'required': _('This field is required.'),
|
||||
'invalid': _('Enter a valid value.'),
|
||||
}
|
||||
|
||||
# Tracks each time a Field instance is created. Used to retain order.
|
||||
@@ -78,7 +78,7 @@ class Field(object):
|
||||
self.required, self.label, self.initial = required, label, initial
|
||||
self.show_hidden_initial = show_hidden_initial
|
||||
if help_text is None:
|
||||
self.help_text = u''
|
||||
self.help_text = ''
|
||||
else:
|
||||
self.help_text = smart_unicode(help_text)
|
||||
widget = widget or self.widget
|
||||
@@ -190,7 +190,7 @@ class CharField(Field):
|
||||
def to_python(self, value):
|
||||
"Returns a Unicode object."
|
||||
if value in validators.EMPTY_VALUES:
|
||||
return u''
|
||||
return ''
|
||||
return smart_unicode(value)
|
||||
|
||||
def widget_attrs(self, widget):
|
||||
@@ -202,9 +202,9 @@ class CharField(Field):
|
||||
|
||||
class IntegerField(Field):
|
||||
default_error_messages = {
|
||||
'invalid': _(u'Enter a whole number.'),
|
||||
'max_value': _(u'Ensure this value is less than or equal to %(limit_value)s.'),
|
||||
'min_value': _(u'Ensure this value is greater than or equal to %(limit_value)s.'),
|
||||
'invalid': _('Enter a whole number.'),
|
||||
'max_value': _('Ensure this value is less than or equal to %(limit_value)s.'),
|
||||
'min_value': _('Ensure this value is greater than or equal to %(limit_value)s.'),
|
||||
}
|
||||
|
||||
def __init__(self, max_value=None, min_value=None, *args, **kwargs):
|
||||
@@ -234,7 +234,7 @@ class IntegerField(Field):
|
||||
|
||||
class FloatField(IntegerField):
|
||||
default_error_messages = {
|
||||
'invalid': _(u'Enter a number.'),
|
||||
'invalid': _('Enter a number.'),
|
||||
}
|
||||
|
||||
def to_python(self, value):
|
||||
@@ -255,9 +255,9 @@ class FloatField(IntegerField):
|
||||
|
||||
class DecimalField(Field):
|
||||
default_error_messages = {
|
||||
'invalid': _(u'Enter a number.'),
|
||||
'max_value': _(u'Ensure this value is less than or equal to %(limit_value)s.'),
|
||||
'min_value': _(u'Ensure this value is greater than or equal to %(limit_value)s.'),
|
||||
'invalid': _('Enter a number.'),
|
||||
'max_value': _('Ensure this value is less than or equal to %(limit_value)s.'),
|
||||
'min_value': _('Ensure this value is greater than or equal to %(limit_value)s.'),
|
||||
'max_digits': _('Ensure that there are no more than %s digits in total.'),
|
||||
'max_decimal_places': _('Ensure that there are no more than %s decimal places.'),
|
||||
'max_whole_digits': _('Ensure that there are no more than %s digits before the decimal point.')
|
||||
@@ -284,7 +284,7 @@ class DecimalField(Field):
|
||||
return None
|
||||
if self.localize:
|
||||
value = formats.sanitize_separators(value)
|
||||
value = smart_str(value).strip()
|
||||
value = smart_unicode(value).strip()
|
||||
try:
|
||||
value = Decimal(value)
|
||||
except DecimalException:
|
||||
@@ -348,7 +348,7 @@ class DateField(BaseTemporalField):
|
||||
widget = DateInput
|
||||
input_formats = formats.get_format_lazy('DATE_INPUT_FORMATS')
|
||||
default_error_messages = {
|
||||
'invalid': _(u'Enter a valid date.'),
|
||||
'invalid': _('Enter a valid date.'),
|
||||
}
|
||||
|
||||
def to_python(self, value):
|
||||
@@ -371,7 +371,7 @@ class TimeField(BaseTemporalField):
|
||||
widget = TimeInput
|
||||
input_formats = formats.get_format_lazy('TIME_INPUT_FORMATS')
|
||||
default_error_messages = {
|
||||
'invalid': _(u'Enter a valid time.')
|
||||
'invalid': _('Enter a valid time.')
|
||||
}
|
||||
|
||||
def to_python(self, value):
|
||||
@@ -392,7 +392,7 @@ class DateTimeField(BaseTemporalField):
|
||||
widget = DateTimeInput
|
||||
input_formats = formats.get_format_lazy('DATETIME_INPUT_FORMATS')
|
||||
default_error_messages = {
|
||||
'invalid': _(u'Enter a valid date/time.'),
|
||||
'invalid': _('Enter a valid date/time.'),
|
||||
}
|
||||
|
||||
def prepare_value(self, value):
|
||||
@@ -457,7 +457,7 @@ class RegexField(CharField):
|
||||
|
||||
class EmailField(CharField):
|
||||
default_error_messages = {
|
||||
'invalid': _(u'Enter a valid e-mail address.'),
|
||||
'invalid': _('Enter a valid e-mail address.'),
|
||||
}
|
||||
default_validators = [validators.validate_email]
|
||||
|
||||
@@ -468,11 +468,11 @@ class EmailField(CharField):
|
||||
class FileField(Field):
|
||||
widget = ClearableFileInput
|
||||
default_error_messages = {
|
||||
'invalid': _(u"No file was submitted. Check the encoding type on the form."),
|
||||
'missing': _(u"No file was submitted."),
|
||||
'empty': _(u"The submitted file is empty."),
|
||||
'max_length': _(u'Ensure this filename has at most %(max)d characters (it has %(length)d).'),
|
||||
'contradiction': _(u'Please either submit a file or check the clear checkbox, not both.')
|
||||
'invalid': _("No file was submitted. Check the encoding type on the form."),
|
||||
'missing': _("No file was submitted."),
|
||||
'empty': _("The submitted file is empty."),
|
||||
'max_length': _('Ensure this filename has at most %(max)d characters (it has %(length)d).'),
|
||||
'contradiction': _('Please either submit a file or check the clear checkbox, not both.')
|
||||
}
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
@@ -527,7 +527,7 @@ class FileField(Field):
|
||||
|
||||
class ImageField(FileField):
|
||||
default_error_messages = {
|
||||
'invalid_image': _(u"Upload a valid image. The file you uploaded was either not an image or a corrupted image."),
|
||||
'invalid_image': _("Upload a valid image. The file you uploaded was either not an image or a corrupted image."),
|
||||
}
|
||||
|
||||
def to_python(self, data):
|
||||
@@ -583,7 +583,7 @@ class ImageField(FileField):
|
||||
|
||||
class URLField(CharField):
|
||||
default_error_messages = {
|
||||
'invalid': _(u'Enter a valid URL.'),
|
||||
'invalid': _('Enter a valid URL.'),
|
||||
}
|
||||
|
||||
def __init__(self, max_length=None, min_length=None, *args, **kwargs):
|
||||
@@ -669,7 +669,7 @@ class NullBooleanField(BooleanField):
|
||||
class ChoiceField(Field):
|
||||
widget = Select
|
||||
default_error_messages = {
|
||||
'invalid_choice': _(u'Select a valid choice. %(value)s is not one of the available choices.'),
|
||||
'invalid_choice': _('Select a valid choice. %(value)s is not one of the available choices.'),
|
||||
}
|
||||
|
||||
def __init__(self, choices=(), required=True, widget=None, label=None,
|
||||
@@ -697,7 +697,7 @@ class ChoiceField(Field):
|
||||
def to_python(self, value):
|
||||
"Returns a Unicode object."
|
||||
if value in validators.EMPTY_VALUES:
|
||||
return u''
|
||||
return ''
|
||||
return smart_unicode(value)
|
||||
|
||||
def validate(self, value):
|
||||
@@ -749,8 +749,8 @@ class MultipleChoiceField(ChoiceField):
|
||||
hidden_widget = MultipleHiddenInput
|
||||
widget = SelectMultiple
|
||||
default_error_messages = {
|
||||
'invalid_choice': _(u'Select a valid choice. %(value)s is not one of the available choices.'),
|
||||
'invalid_list': _(u'Enter a list of values.'),
|
||||
'invalid_choice': _('Select a valid choice. %(value)s is not one of the available choices.'),
|
||||
'invalid_list': _('Enter a list of values.'),
|
||||
}
|
||||
|
||||
def to_python(self, value):
|
||||
@@ -838,7 +838,7 @@ class MultiValueField(Field):
|
||||
You'll probably want to use this with MultiWidget.
|
||||
"""
|
||||
default_error_messages = {
|
||||
'invalid': _(u'Enter a list of values.'),
|
||||
'invalid': _('Enter a list of values.'),
|
||||
}
|
||||
|
||||
def __init__(self, fields=(), *args, **kwargs):
|
||||
@@ -956,8 +956,8 @@ class SplitDateTimeField(MultiValueField):
|
||||
widget = SplitDateTimeWidget
|
||||
hidden_widget = SplitHiddenDateTimeWidget
|
||||
default_error_messages = {
|
||||
'invalid_date': _(u'Enter a valid date.'),
|
||||
'invalid_time': _(u'Enter a valid time.'),
|
||||
'invalid_date': _('Enter a valid date.'),
|
||||
'invalid_time': _('Enter a valid time.'),
|
||||
}
|
||||
|
||||
def __init__(self, input_date_formats=None, input_time_formats=None, *args, **kwargs):
|
||||
@@ -990,7 +990,7 @@ class SplitDateTimeField(MultiValueField):
|
||||
|
||||
class IPAddressField(CharField):
|
||||
default_error_messages = {
|
||||
'invalid': _(u'Enter a valid IPv4 address.'),
|
||||
'invalid': _('Enter a valid IPv4 address.'),
|
||||
}
|
||||
default_validators = [validators.validate_ipv4_address]
|
||||
|
||||
@@ -1007,7 +1007,7 @@ class GenericIPAddressField(CharField):
|
||||
|
||||
def to_python(self, value):
|
||||
if value in validators.EMPTY_VALUES:
|
||||
return u''
|
||||
return ''
|
||||
if value and ':' in value:
|
||||
return clean_ipv6_address(value,
|
||||
self.unpack_ipv4, self.error_messages['invalid'])
|
||||
@@ -1016,7 +1016,7 @@ class GenericIPAddressField(CharField):
|
||||
|
||||
class SlugField(CharField):
|
||||
default_error_messages = {
|
||||
'invalid': _(u"Enter a valid 'slug' consisting of letters, numbers,"
|
||||
u" underscores or hyphens."),
|
||||
'invalid': _("Enter a valid 'slug' consisting of letters, numbers,"
|
||||
" underscores or hyphens."),
|
||||
}
|
||||
default_validators = [validators.validate_slug]
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
Form classes
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import copy
|
||||
|
||||
@@ -23,7 +23,7 @@ NON_FIELD_ERRORS = '__all__'
|
||||
def pretty_name(name):
|
||||
"""Converts 'first_name' to 'First name'"""
|
||||
if not name:
|
||||
return u''
|
||||
return ''
|
||||
return name.replace('_', ' ').capitalize()
|
||||
|
||||
def get_declared_fields(bases, attrs, with_base_fields=True):
|
||||
@@ -136,7 +136,7 @@ class BaseForm(StrAndUnicode):
|
||||
"""
|
||||
Add a 'initial' prefix for checking dynamic initial values
|
||||
"""
|
||||
return u'initial-%s' % self.add_prefix(field_name)
|
||||
return 'initial-%s' % self.add_prefix(field_name)
|
||||
|
||||
def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row):
|
||||
"Helper function for outputting HTML. Used by as_table(), as_ul(), as_p()."
|
||||
@@ -149,7 +149,7 @@ class BaseForm(StrAndUnicode):
|
||||
bf_errors = self.error_class([conditional_escape(error) for error in bf.errors]) # Escape and cache in local variable.
|
||||
if bf.is_hidden:
|
||||
if bf_errors:
|
||||
top_errors.extend([u'(Hidden field %s) %s' % (name, force_unicode(e)) for e in bf_errors])
|
||||
top_errors.extend(['(Hidden field %s) %s' % (name, force_unicode(e)) for e in bf_errors])
|
||||
hidden_fields.append(unicode(bf))
|
||||
else:
|
||||
# Create a 'class="..."' atribute if the row should have any
|
||||
@@ -175,7 +175,7 @@ class BaseForm(StrAndUnicode):
|
||||
if field.help_text:
|
||||
help_text = help_text_html % force_unicode(field.help_text)
|
||||
else:
|
||||
help_text = u''
|
||||
help_text = ''
|
||||
|
||||
output.append(normal_row % {
|
||||
'errors': force_unicode(bf_errors),
|
||||
@@ -189,7 +189,7 @@ class BaseForm(StrAndUnicode):
|
||||
output.insert(0, error_row % force_unicode(top_errors))
|
||||
|
||||
if hidden_fields: # Insert any hidden fields in the last row.
|
||||
str_hidden = u''.join(hidden_fields)
|
||||
str_hidden = ''.join(hidden_fields)
|
||||
if output:
|
||||
last_row = output[-1]
|
||||
# Chop off the trailing row_ender (e.g. '</td></tr>') and
|
||||
@@ -208,33 +208,33 @@ class BaseForm(StrAndUnicode):
|
||||
# If there aren't any rows in the output, just append the
|
||||
# hidden fields.
|
||||
output.append(str_hidden)
|
||||
return mark_safe(u'\n'.join(output))
|
||||
return mark_safe('\n'.join(output))
|
||||
|
||||
def as_table(self):
|
||||
"Returns this form rendered as HTML <tr>s -- excluding the <table></table>."
|
||||
return self._html_output(
|
||||
normal_row = u'<tr%(html_class_attr)s><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>',
|
||||
error_row = u'<tr><td colspan="2">%s</td></tr>',
|
||||
row_ender = u'</td></tr>',
|
||||
help_text_html = u'<br /><span class="helptext">%s</span>',
|
||||
normal_row = '<tr%(html_class_attr)s><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>',
|
||||
error_row = '<tr><td colspan="2">%s</td></tr>',
|
||||
row_ender = '</td></tr>',
|
||||
help_text_html = '<br /><span class="helptext">%s</span>',
|
||||
errors_on_separate_row = False)
|
||||
|
||||
def as_ul(self):
|
||||
"Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
|
||||
return self._html_output(
|
||||
normal_row = u'<li%(html_class_attr)s>%(errors)s%(label)s %(field)s%(help_text)s</li>',
|
||||
error_row = u'<li>%s</li>',
|
||||
normal_row = '<li%(html_class_attr)s>%(errors)s%(label)s %(field)s%(help_text)s</li>',
|
||||
error_row = '<li>%s</li>',
|
||||
row_ender = '</li>',
|
||||
help_text_html = u' <span class="helptext">%s</span>',
|
||||
help_text_html = ' <span class="helptext">%s</span>',
|
||||
errors_on_separate_row = False)
|
||||
|
||||
def as_p(self):
|
||||
"Returns this form rendered as HTML <p>s."
|
||||
return self._html_output(
|
||||
normal_row = u'<p%(html_class_attr)s>%(label)s %(field)s%(help_text)s</p>',
|
||||
error_row = u'%s',
|
||||
normal_row = '<p%(html_class_attr)s>%(label)s %(field)s%(help_text)s</p>',
|
||||
error_row = '%s',
|
||||
row_ender = '</p>',
|
||||
help_text_html = u' <span class="helptext">%s</span>',
|
||||
help_text_html = ' <span class="helptext">%s</span>',
|
||||
errors_on_separate_row = True)
|
||||
|
||||
def non_field_errors(self):
|
||||
@@ -508,7 +508,7 @@ class BoundField(StrAndUnicode):
|
||||
id_ = widget.attrs.get('id') or self.auto_id
|
||||
if id_:
|
||||
attrs = attrs and flatatt(attrs) or ''
|
||||
contents = u'<label for="%s"%s>%s</label>' % (widget.id_for_label(id_), attrs, unicode(contents))
|
||||
contents = '<label for="%s"%s>%s</label>' % (widget.id_for_label(id_), attrs, unicode(contents))
|
||||
return mark_safe(contents)
|
||||
|
||||
def css_classes(self, extra_classes=None):
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from __future__ import absolute_import
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.forms import Form
|
||||
@@ -314,11 +314,11 @@ class BaseFormSet(StrAndUnicode):
|
||||
if self.can_order:
|
||||
# Only pre-fill the ordering field for initial forms.
|
||||
if index is not None and index < self.initial_form_count():
|
||||
form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_(u'Order'), initial=index+1, required=False)
|
||||
form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_('Order'), initial=index+1, required=False)
|
||||
else:
|
||||
form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_(u'Order'), required=False)
|
||||
form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_('Order'), required=False)
|
||||
if self.can_delete:
|
||||
form.fields[DELETION_FIELD_NAME] = BooleanField(label=_(u'Delete'), required=False)
|
||||
form.fields[DELETION_FIELD_NAME] = BooleanField(label=_('Delete'), required=False)
|
||||
|
||||
def add_prefix(self, index):
|
||||
return '%s-%s' % (self.prefix, index)
|
||||
@@ -344,18 +344,18 @@ class BaseFormSet(StrAndUnicode):
|
||||
# XXX: there is no semantic division between forms here, there
|
||||
# probably should be. It might make sense to render each form as a
|
||||
# table row with each field as a td.
|
||||
forms = u' '.join([form.as_table() for form in self])
|
||||
return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
|
||||
forms = ' '.join([form.as_table() for form in self])
|
||||
return mark_safe('\n'.join([unicode(self.management_form), forms]))
|
||||
|
||||
def as_p(self):
|
||||
"Returns this formset rendered as HTML <p>s."
|
||||
forms = u' '.join([form.as_p() for form in self])
|
||||
return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
|
||||
forms = ' '.join([form.as_p() for form in self])
|
||||
return mark_safe('\n'.join([unicode(self.management_form), forms]))
|
||||
|
||||
def as_ul(self):
|
||||
"Returns this formset rendered as HTML <li>s."
|
||||
forms = u' '.join([form.as_ul() for form in self])
|
||||
return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
|
||||
forms = ' '.join([form.as_ul() for form in self])
|
||||
return mark_safe('\n'.join([unicode(self.management_form), forms]))
|
||||
|
||||
def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
|
||||
can_delete=False, max_num=None):
|
||||
@@ -363,7 +363,7 @@ def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
|
||||
attrs = {'form': form, 'extra': extra,
|
||||
'can_order': can_order, 'can_delete': can_delete,
|
||||
'max_num': max_num}
|
||||
return type(form.__name__ + 'FormSet', (formset,), attrs)
|
||||
return type(form.__name__ + b'FormSet', (formset,), attrs)
|
||||
|
||||
def all_valid(formsets):
|
||||
"""Returns true if every formset in formsets is valid."""
|
||||
|
||||
@@ -3,7 +3,7 @@ Helper functions for creating Form classes from Django models
|
||||
and database field objects.
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
from django.core.exceptions import ValidationError, NON_FIELD_ERRORS, FieldError
|
||||
from django.core.validators import EMPTY_VALUES
|
||||
@@ -846,7 +846,7 @@ class InlineForeignKeyField(Field):
|
||||
given parent instance in an inline.
|
||||
"""
|
||||
default_error_messages = {
|
||||
'invalid_choice': _(u'The inline foreign key did not match the parent instance primary key.'),
|
||||
'invalid_choice': _('The inline foreign key did not match the parent instance primary key.'),
|
||||
}
|
||||
|
||||
def __init__(self, parent_instance, *args, **kwargs):
|
||||
@@ -884,7 +884,7 @@ class ModelChoiceIterator(object):
|
||||
|
||||
def __iter__(self):
|
||||
if self.field.empty_label is not None:
|
||||
yield (u"", self.field.empty_label)
|
||||
yield ("", self.field.empty_label)
|
||||
if self.field.cache_choices:
|
||||
if self.field.choice_cache is None:
|
||||
self.field.choice_cache = [
|
||||
@@ -907,11 +907,11 @@ class ModelChoiceField(ChoiceField):
|
||||
# This class is a subclass of ChoiceField for purity, but it doesn't
|
||||
# actually use any of ChoiceField's implementation.
|
||||
default_error_messages = {
|
||||
'invalid_choice': _(u'Select a valid choice. That choice is not one of'
|
||||
u' the available choices.'),
|
||||
'invalid_choice': _('Select a valid choice. That choice is not one of'
|
||||
' the available choices.'),
|
||||
}
|
||||
|
||||
def __init__(self, queryset, empty_label=u"---------", cache_choices=False,
|
||||
def __init__(self, queryset, empty_label="---------", cache_choices=False,
|
||||
required=True, widget=None, label=None, initial=None,
|
||||
help_text=None, to_field_name=None, *args, **kwargs):
|
||||
if required and (initial is not None):
|
||||
@@ -996,10 +996,10 @@ class ModelMultipleChoiceField(ModelChoiceField):
|
||||
widget = SelectMultiple
|
||||
hidden_widget = MultipleHiddenInput
|
||||
default_error_messages = {
|
||||
'list': _(u'Enter a list of values.'),
|
||||
'invalid_choice': _(u'Select a valid choice. %s is not one of the'
|
||||
u' available choices.'),
|
||||
'invalid_pk_value': _(u'"%s" is not a valid value for a primary key.')
|
||||
'list': _('Enter a list of values.'),
|
||||
'invalid_choice': _('Select a valid choice. %s is not one of the'
|
||||
' available choices.'),
|
||||
'invalid_pk_value': _('"%s" is not a valid value for a primary key.')
|
||||
}
|
||||
|
||||
def __init__(self, queryset, cache_choices=False, required=True,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.conf import settings
|
||||
from django.utils.html import conditional_escape
|
||||
from django.utils.encoding import StrAndUnicode, force_unicode
|
||||
@@ -16,7 +18,7 @@ def flatatt(attrs):
|
||||
XML-style pairs. It is assumed that the keys do not need to be XML-escaped.
|
||||
If the passed dictionary is empty, then return an empty string.
|
||||
"""
|
||||
return u''.join([u' %s="%s"' % (k, conditional_escape(v)) for k, v in attrs.items()])
|
||||
return ''.join([' %s="%s"' % (k, conditional_escape(v)) for k, v in attrs.items()])
|
||||
|
||||
class ErrorDict(dict, StrAndUnicode):
|
||||
"""
|
||||
@@ -28,13 +30,13 @@ class ErrorDict(dict, StrAndUnicode):
|
||||
return self.as_ul()
|
||||
|
||||
def as_ul(self):
|
||||
if not self: return u''
|
||||
return mark_safe(u'<ul class="errorlist">%s</ul>'
|
||||
% ''.join([u'<li>%s%s</li>' % (k, conditional_escape(force_unicode(v)))
|
||||
if not self: return ''
|
||||
return mark_safe('<ul class="errorlist">%s</ul>'
|
||||
% ''.join(['<li>%s%s</li>' % (k, conditional_escape(force_unicode(v)))
|
||||
for k, v in self.items()]))
|
||||
|
||||
def as_text(self):
|
||||
return u'\n'.join([u'* %s\n%s' % (k, u'\n'.join([u' * %s' % force_unicode(i) for i in v])) for k, v in self.items()])
|
||||
return '\n'.join(['* %s\n%s' % (k, '\n'.join([' * %s' % force_unicode(i) for i in v])) for k, v in self.items()])
|
||||
|
||||
class ErrorList(list, StrAndUnicode):
|
||||
"""
|
||||
@@ -44,13 +46,13 @@ class ErrorList(list, StrAndUnicode):
|
||||
return self.as_ul()
|
||||
|
||||
def as_ul(self):
|
||||
if not self: return u''
|
||||
return mark_safe(u'<ul class="errorlist">%s</ul>'
|
||||
% ''.join([u'<li>%s</li>' % conditional_escape(force_unicode(e)) for e in self]))
|
||||
if not self: return ''
|
||||
return mark_safe('<ul class="errorlist">%s</ul>'
|
||||
% ''.join(['<li>%s</li>' % conditional_escape(force_unicode(e)) for e in self]))
|
||||
|
||||
def as_text(self):
|
||||
if not self: return u''
|
||||
return u'\n'.join([u'* %s' % force_unicode(e) for e in self])
|
||||
if not self: return ''
|
||||
return '\n'.join(['* %s' % force_unicode(e) for e in self])
|
||||
|
||||
def __repr__(self):
|
||||
return repr([force_unicode(e) for e in self])
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
HTML Widget classes
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import copy
|
||||
import datetime
|
||||
@@ -50,10 +50,10 @@ class Media(StrAndUnicode):
|
||||
return self.render()
|
||||
|
||||
def render(self):
|
||||
return mark_safe(u'\n'.join(chain(*[getattr(self, 'render_' + name)() for name in MEDIA_TYPES])))
|
||||
return mark_safe('\n'.join(chain(*[getattr(self, 'render_' + name)() for name in MEDIA_TYPES])))
|
||||
|
||||
def render_js(self):
|
||||
return [u'<script type="text/javascript" src="%s"></script>' % self.absolute_path(path) for path in self._js]
|
||||
return ['<script type="text/javascript" src="%s"></script>' % self.absolute_path(path) for path in self._js]
|
||||
|
||||
def render_css(self):
|
||||
# To keep rendering order consistent, we can't just iterate over items().
|
||||
@@ -61,12 +61,12 @@ class Media(StrAndUnicode):
|
||||
media = self._css.keys()
|
||||
media.sort()
|
||||
return chain(*[
|
||||
[u'<link href="%s" type="text/css" media="%s" rel="stylesheet" />' % (self.absolute_path(path), medium)
|
||||
['<link href="%s" type="text/css" media="%s" rel="stylesheet" />' % (self.absolute_path(path), medium)
|
||||
for path in self._css[medium]]
|
||||
for medium in media])
|
||||
|
||||
def absolute_path(self, path, prefix=None):
|
||||
if path.startswith(u'http://') or path.startswith(u'https://') or path.startswith(u'/'):
|
||||
if path.startswith(('http://', 'https://', '/')):
|
||||
return path
|
||||
if prefix is None:
|
||||
if settings.STATIC_URL is None:
|
||||
@@ -210,13 +210,13 @@ class Widget(object):
|
||||
"""
|
||||
# For purposes of seeing whether something has changed, None is
|
||||
# the same as an empty string, if the data or inital value we get
|
||||
# is None, replace it w/ u''.
|
||||
# is None, replace it w/ ''.
|
||||
if data is None:
|
||||
data_value = u''
|
||||
data_value = ''
|
||||
else:
|
||||
data_value = data
|
||||
if initial is None:
|
||||
initial_value = u''
|
||||
initial_value = ''
|
||||
else:
|
||||
initial_value = initial
|
||||
if force_unicode(initial_value) != force_unicode(data_value):
|
||||
@@ -254,7 +254,7 @@ class Input(Widget):
|
||||
if value != '':
|
||||
# Only add the 'value' attribute if a value is non-empty.
|
||||
final_attrs['value'] = force_unicode(self._format_value(value))
|
||||
return mark_safe(u'<input%s />' % flatatt(final_attrs))
|
||||
return mark_safe('<input%s />' % flatatt(final_attrs))
|
||||
|
||||
class TextInput(Input):
|
||||
input_type = 'text'
|
||||
@@ -295,8 +295,8 @@ class MultipleHiddenInput(HiddenInput):
|
||||
# An ID attribute was given. Add a numeric index as a suffix
|
||||
# so that the inputs don't all have the same ID attribute.
|
||||
input_attrs['id'] = '%s_%s' % (id_, i)
|
||||
inputs.append(u'<input%s />' % flatatt(input_attrs))
|
||||
return mark_safe(u'\n'.join(inputs))
|
||||
inputs.append('<input%s />' % flatatt(input_attrs))
|
||||
return mark_safe('\n'.join(inputs))
|
||||
|
||||
def value_from_datadict(self, data, files, name):
|
||||
if isinstance(data, (MultiValueDict, MergeDict)):
|
||||
@@ -326,9 +326,9 @@ class ClearableFileInput(FileInput):
|
||||
input_text = ugettext_lazy('Change')
|
||||
clear_checkbox_label = ugettext_lazy('Clear')
|
||||
|
||||
template_with_initial = u'%(initial_text)s: %(initial)s %(clear_template)s<br />%(input_text)s: %(input)s'
|
||||
template_with_initial = '%(initial_text)s: %(initial)s %(clear_template)s<br />%(input_text)s: %(input)s'
|
||||
|
||||
template_with_clear = u'%(clear)s <label for="%(clear_checkbox_id)s">%(clear_checkbox_label)s</label>'
|
||||
template_with_clear = '%(clear)s <label for="%(clear_checkbox_id)s">%(clear_checkbox_label)s</label>'
|
||||
|
||||
def clear_checkbox_name(self, name):
|
||||
"""
|
||||
@@ -350,12 +350,12 @@ class ClearableFileInput(FileInput):
|
||||
'clear_template': '',
|
||||
'clear_checkbox_label': self.clear_checkbox_label,
|
||||
}
|
||||
template = u'%(input)s'
|
||||
template = '%(input)s'
|
||||
substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs)
|
||||
|
||||
if value and hasattr(value, "url"):
|
||||
template = self.template_with_initial
|
||||
substitutions['initial'] = (u'<a href="%s">%s</a>'
|
||||
substitutions['initial'] = ('<a href="%s">%s</a>'
|
||||
% (escape(value.url),
|
||||
escape(force_unicode(value))))
|
||||
if not self.is_required:
|
||||
@@ -392,7 +392,7 @@ class Textarea(Widget):
|
||||
def render(self, name, value, attrs=None):
|
||||
if value is None: value = ''
|
||||
final_attrs = self.build_attrs(attrs, name=name)
|
||||
return mark_safe(u'<textarea%s>%s</textarea>' % (flatatt(final_attrs),
|
||||
return mark_safe('<textarea%s>%s</textarea>' % (flatatt(final_attrs),
|
||||
conditional_escape(force_unicode(value))))
|
||||
|
||||
class DateInput(Input):
|
||||
@@ -511,7 +511,7 @@ class CheckboxInput(Widget):
|
||||
if not (value is True or value is False or value is None or value == ''):
|
||||
# Only add the 'value' attribute if a value is non-empty.
|
||||
final_attrs['value'] = force_unicode(value)
|
||||
return mark_safe(u'<input%s />' % flatatt(final_attrs))
|
||||
return mark_safe('<input%s />' % flatatt(final_attrs))
|
||||
|
||||
def value_from_datadict(self, data, files, name):
|
||||
if name not in data:
|
||||
@@ -526,7 +526,7 @@ class CheckboxInput(Widget):
|
||||
return value
|
||||
|
||||
def _has_changed(self, initial, data):
|
||||
# Sometimes data or initial could be None or u'' which should be the
|
||||
# Sometimes data or initial could be None or '' which should be the
|
||||
# same thing as False.
|
||||
return bool(initial) != bool(data)
|
||||
|
||||
@@ -543,23 +543,23 @@ class Select(Widget):
|
||||
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)]
|
||||
output = ['<select%s>' % flatatt(final_attrs)]
|
||||
options = self.render_options(choices, [value])
|
||||
if options:
|
||||
output.append(options)
|
||||
output.append(u'</select>')
|
||||
return mark_safe(u'\n'.join(output))
|
||||
output.append('</select>')
|
||||
return mark_safe('\n'.join(output))
|
||||
|
||||
def render_option(self, selected_choices, option_value, option_label):
|
||||
option_value = force_unicode(option_value)
|
||||
if option_value in selected_choices:
|
||||
selected_html = u' selected="selected"'
|
||||
selected_html = ' selected="selected"'
|
||||
if not self.allow_multiple_selected:
|
||||
# Only allow for a single selection.
|
||||
selected_choices.remove(option_value)
|
||||
else:
|
||||
selected_html = ''
|
||||
return u'<option value="%s"%s>%s</option>' % (
|
||||
return '<option value="%s"%s>%s</option>' % (
|
||||
escape(option_value), selected_html,
|
||||
conditional_escape(force_unicode(option_label)))
|
||||
|
||||
@@ -569,37 +569,37 @@ class Select(Widget):
|
||||
output = []
|
||||
for option_value, option_label in chain(self.choices, choices):
|
||||
if isinstance(option_label, (list, tuple)):
|
||||
output.append(u'<optgroup label="%s">' % escape(force_unicode(option_value)))
|
||||
output.append('<optgroup label="%s">' % escape(force_unicode(option_value)))
|
||||
for option in option_label:
|
||||
output.append(self.render_option(selected_choices, *option))
|
||||
output.append(u'</optgroup>')
|
||||
output.append('</optgroup>')
|
||||
else:
|
||||
output.append(self.render_option(selected_choices, option_value, option_label))
|
||||
return u'\n'.join(output)
|
||||
return '\n'.join(output)
|
||||
|
||||
class NullBooleanSelect(Select):
|
||||
"""
|
||||
A Select Widget intended to be used with NullBooleanField.
|
||||
"""
|
||||
def __init__(self, attrs=None):
|
||||
choices = ((u'1', ugettext_lazy('Unknown')),
|
||||
(u'2', ugettext_lazy('Yes')),
|
||||
(u'3', ugettext_lazy('No')))
|
||||
choices = (('1', ugettext_lazy('Unknown')),
|
||||
('2', ugettext_lazy('Yes')),
|
||||
('3', ugettext_lazy('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]
|
||||
value = {True: '2', False: '3', '2': '2', '3': '3'}[value]
|
||||
except KeyError:
|
||||
value = u'1'
|
||||
value = '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,
|
||||
return {'2': True,
|
||||
True: True,
|
||||
'True': True,
|
||||
u'3': False,
|
||||
'3': False,
|
||||
'False': False,
|
||||
False: False}.get(value, None)
|
||||
|
||||
@@ -618,12 +618,12 @@ class SelectMultiple(Select):
|
||||
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)]
|
||||
output = ['<select multiple="multiple"%s>' % flatatt(final_attrs)]
|
||||
options = self.render_options(choices, value)
|
||||
if options:
|
||||
output.append(options)
|
||||
output.append('</select>')
|
||||
return mark_safe(u'\n'.join(output))
|
||||
return mark_safe('\n'.join(output))
|
||||
|
||||
def value_from_datadict(self, data, files, name):
|
||||
if isinstance(data, (MultiValueDict, MergeDict)):
|
||||
@@ -666,7 +666,7 @@ class RadioInput(SubWidget):
|
||||
else:
|
||||
label_for = ''
|
||||
choice_label = conditional_escape(force_unicode(self.choice_label))
|
||||
return mark_safe(u'<label%s>%s %s</label>' % (label_for, self.tag(), choice_label))
|
||||
return mark_safe('<label%s>%s %s</label>' % (label_for, self.tag(), choice_label))
|
||||
|
||||
def is_checked(self):
|
||||
return self.value == self.choice_value
|
||||
@@ -677,7 +677,7 @@ class RadioInput(SubWidget):
|
||||
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'<input%s />' % flatatt(final_attrs))
|
||||
return mark_safe('<input%s />' % flatatt(final_attrs))
|
||||
|
||||
class RadioFieldRenderer(StrAndUnicode):
|
||||
"""
|
||||
@@ -701,7 +701,7 @@ class RadioFieldRenderer(StrAndUnicode):
|
||||
|
||||
def render(self):
|
||||
"""Outputs a <ul> for this set of radio fields."""
|
||||
return mark_safe(u'<ul>\n%s\n</ul>' % u'\n'.join([u'<li>%s</li>'
|
||||
return mark_safe('<ul>\n%s\n</ul>' % '\n'.join(['<li>%s</li>'
|
||||
% force_unicode(w) for w in self]))
|
||||
|
||||
class RadioSelect(Select):
|
||||
@@ -743,7 +743,7 @@ class CheckboxSelectMultiple(SelectMultiple):
|
||||
if value is None: value = []
|
||||
has_id = attrs and 'id' in attrs
|
||||
final_attrs = self.build_attrs(attrs, name=name)
|
||||
output = [u'<ul>']
|
||||
output = ['<ul>']
|
||||
# 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)):
|
||||
@@ -751,7 +751,7 @@ class CheckboxSelectMultiple(SelectMultiple):
|
||||
# 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']
|
||||
label_for = ' for="%s"' % final_attrs['id']
|
||||
else:
|
||||
label_for = ''
|
||||
|
||||
@@ -759,9 +759,9 @@ class CheckboxSelectMultiple(SelectMultiple):
|
||||
option_value = force_unicode(option_value)
|
||||
rendered_cb = cb.render(name, option_value)
|
||||
option_label = conditional_escape(force_unicode(option_label))
|
||||
output.append(u'<li><label%s>%s %s</label></li>' % (label_for, rendered_cb, option_label))
|
||||
output.append(u'</ul>')
|
||||
return mark_safe(u'\n'.join(output))
|
||||
output.append('<li><label%s>%s %s</label></li>' % (label_for, rendered_cb, option_label))
|
||||
output.append('</ul>')
|
||||
return mark_safe('\n'.join(output))
|
||||
|
||||
def id_for_label(self, id_):
|
||||
# See the comment for RadioSelect.id_for_label()
|
||||
@@ -832,7 +832,7 @@ class MultiWidget(Widget):
|
||||
|
||||
def _has_changed(self, initial, data):
|
||||
if initial is None:
|
||||
initial = [u'' for x in range(0, len(data))]
|
||||
initial = ['' for x in range(0, len(data))]
|
||||
else:
|
||||
if not isinstance(initial, list):
|
||||
initial = self.decompress(initial)
|
||||
@@ -849,7 +849,7 @@ class MultiWidget(Widget):
|
||||
This hook allows you to format the HTML design of the widgets, if
|
||||
needed.
|
||||
"""
|
||||
return u''.join(rendered_widgets)
|
||||
return ''.join(rendered_widgets)
|
||||
|
||||
def decompress(self, value):
|
||||
"""
|
||||
|
||||
Reference in New Issue
Block a user