Ticket #15287: patch2.diff

File patch2.diff, 19.0 KB (added by szczav, 4 years ago)
  • views/generic/base.py

     
    55from django.utils.functional import update_wrapper
    66from django.utils.log import getLogger
    77from django.utils.decorators import classonlymethod
     8from django.utils.translation import ugettext as _
    89
    910logger = getLogger('django.request')
    1011
     
    3536        # sanitize keyword arguments
    3637        for key in initkwargs:
    3738            if key in cls.http_method_names:
    38                 raise TypeError(u"You tried to pass in the %s method name as a "
    39                                 u"keyword argument to %s(). Don't do that."
    40                                 % (key, cls.__name__))
     39                raise TypeError(_("You tried to pass in the %(kwarg)s method "
     40                                  "name as a keyword argument to "
     41                                  "%(class_name)s(). Don't do that.")
     42                                % {'kwarg': key,
     43                                   'class_name': cls.__name__})
    4144            if not hasattr(cls, key):
    42                 raise TypeError(u"%s() received an invalid keyword %r" % (
    43                     cls.__name__, key))
     45                raise TypeError(_("%(class_name)s() received an invalid keyword %(kwarg)s")
     46                                % {'class_name': cls.__name__,
     47                                   'kwarg': key})
    4448
    4549        def view(request, *args, **kwargs):
    4650            self = cls(**initkwargs)
  • views/generic/date_based.py

     
    66from django.core.xheaders import populate_xheaders
    77from django.db.models.fields import DateTimeField
    88from django.http import Http404, HttpResponse
     9from django.utils.encoding import force_unicode
     10from django.utils.translation import ugettext as _
    911
    1012import warnings
    1113warnings.warn(
     
    3436        queryset = queryset.filter(**{'%s__lte' % date_field: datetime.datetime.now()})
    3537    date_list = queryset.dates(date_field, 'year')[::-1]
    3638    if not date_list and not allow_empty:
    37         raise Http404("No %s available" % model._meta.verbose_name)
     39        raise Http404(_("No %(verbose_name)s available")
     40                % {'verbose_name': force_unicode(model._meta.verbose_name)})
    3841
    3942    if date_list and num_latest:
    4043        latest = queryset.order_by('-'+date_field)[:num_latest]
     
    350353    elif slug and slug_field:
    351354        lookup_kwargs['%s__exact' % slug_field] = slug
    352355    else:
    353         raise AttributeError("Generic detail view must be called with either an object_id or a slug/slugfield")
     356        raise AttributeError(_("Generic detail view must be called with either"
     357                               " an object_id or a slug/slugfield"))
    354358    try:
    355359        obj = queryset.get(**lookup_kwargs)
    356360    except ObjectDoesNotExist:
    357         raise Http404("No %s found for" % model._meta.verbose_name)
     361        raise Http404(_("No %(verbose_name)s found for")
     362                % {'verbose_name': force_unicode(model._meta.verbose_name)})
    358363    if not template_name:
    359364        template_name = "%s/%s_detail.html" % (model._meta.app_label, model._meta.object_name.lower())
    360365    if template_name_field:
  • views/generic/list.py

     
    55from django.http import Http404
    66from django.utils.encoding import smart_str
    77from django.views.generic.base import TemplateResponseMixin, View
     8from django.utils.translation import ugettext as _
     9from django.utils.encoding import force_unicode
    810
    911
    1012class MultipleObjectMixin(object):
     
    2729        elif self.model is not None:
    2830            queryset = self.model._default_manager.all()
    2931        else:
    30             raise ImproperlyConfigured(u"'%s' must define 'queryset' or 'model'"
    31                                        % self.__class__.__name__)
     32            raise ImproperlyConfigured(_("'%(class_name)s' must define 'queryset' or 'model'")
     33                                       % {'class_name': self.__class__.__name__})
    3234        return queryset
    3335
    3436    def paginate_queryset(self, queryset, page_size):
     
    4345            if page == 'last':
    4446                page_number = paginator.num_pages
    4547            else:
    46                 raise Http404("Page is not 'last', nor can it be converted to an int.")
     48                raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    4749        try:
    4850            page = paginator.page(page_number)
    4951            return (paginator, page, page.object_list, True)
    5052        except InvalidPage:
    51             raise Http404(u'Invalid page (%s)' % page_number)
     53            raise Http404(_('Invalid page (%(page_number)s)')
     54                    % {'page_number': page_number})
    5255
    5356    def get_paginate_by(self, queryset):
    5457        """
     
    114117        self.object_list = self.get_queryset()
    115118        allow_empty = self.get_allow_empty()
    116119        if not allow_empty and len(self.object_list) == 0:
    117             raise Http404(u"Empty list and '%s.allow_empty' is False."
    118                           % self.__class__.__name__)
     120            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
     121                          % {'class_name': self.__class__.__name__})
    119122        context = self.get_context_data(object_list=self.object_list)
    120123        return self.render_to_response(context)
    121124
  • views/generic/list_detail.py

     
    33from django.core.xheaders import populate_xheaders
    44from django.core.paginator import Paginator, InvalidPage
    55from django.core.exceptions import ObjectDoesNotExist
     6from django.utils.translation import ugettext as _
     7from django.utils.encoding import force_unicode
    68
    79import warnings
    810warnings.warn(
     
    127129    elif slug and slug_field:
    128130        queryset = queryset.filter(**{slug_field: slug})
    129131    else:
    130         raise AttributeError("Generic detail view must be called with either an object_id or a slug/slug_field.")
     132        raise AttributeError(_("Generic detail view must be called with "
     133                               "either an object_id or a slug/slug_field."))
    131134    try:
    132135        obj = queryset.get()
    133136    except ObjectDoesNotExist:
    134         raise Http404("No %s found matching the query" % (model._meta.verbose_name))
     137        raise Http404(_("No %(verbose_name)s found matching the query")
     138                % {'verbose_name': force_unicode(model._meta.verbose_name)})
    135139    if not template_name:
    136140        template_name = "%s/%s_detail.html" % (model._meta.app_label, model._meta.object_name.lower())
    137141    if template_name_field:
  • views/generic/dates.py

     
    66from django.views.generic.base import View
    77from django.views.generic.detail import BaseDetailView, SingleObjectTemplateResponseMixin
    88from django.views.generic.list import MultipleObjectMixin, MultipleObjectTemplateResponseMixin
     9from django.utils.translation import ugettext as _
     10from django.utils.encoding import force_unicode
    911
    1012
    1113class YearMixin(object):
     
    2931                try:
    3032                    year = self.request.GET['year']
    3133                except KeyError:
    32                     raise Http404("No year specified")
     34                    raise Http404(_("No year specified"))
    3335        return year
    3436
    3537
     
    5456                try:
    5557                    month = self.request.GET['month']
    5658                except KeyError:
    57                     raise Http404("No month specified")
     59                    raise Http404(_("No month specified"))
    5860        return month
    5961
    6062    def get_next_month(self, date):
     
    9597                try:
    9698                    day = self.request.GET['day']
    9799                except KeyError:
    98                     raise Http404("No day specified")
     100                    raise Http404(_("No day specified"))
    99101        return day
    100102
    101103    def get_next_day(self, date):
     
    134136                try:
    135137                    week = self.request.GET['week']
    136138                except KeyError:
    137                     raise Http404("No week specified")
     139                    raise Http404(_("No week specified"))
    138140        return week
    139141
    140142
     
    150152        Get the name of the date field to be used to filter by.
    151153        """
    152154        if self.date_field is None:
    153             raise ImproperlyConfigured(u"%s.date_field is required." % self.__class__.__name__)
     155            raise ImproperlyConfigured(_("%(class_name)s.date_field is required.")
     156                    % {'class_name': self.__class__.__name__})
    154157        return self.date_field
    155158
    156159    def get_allow_future(self):
     
    178181        """
    179182        Obtain the list of dates and itesm
    180183        """
    181         raise NotImplementedError('A DateView must provide an implementation of get_dated_items()')
     184        raise NotImplementedError(_('A DateView must provide an implementation of get_dated_items()'))
    182185
    183186    def get_dated_queryset(self, **lookup):
    184187        """
     
    194197            qs = qs.filter(**{'%s__lte' % date_field: datetime.datetime.now()})
    195198
    196199        if not allow_empty and not qs:
    197             raise Http404(u"No %s available" % unicode(qs.model._meta.verbose_name_plural))
     200            raise Http404(_("No %(verbose_name_plural)s available")
     201                    % {'verbose_name_plural': force_unicode(qs.model._meta.verbose_name_plural)})
    198202
    199203        return qs
    200204
     
    208212
    209213        date_list = queryset.dates(date_field, date_type)[::-1]
    210214        if date_list is not None and not date_list and not allow_empty:
    211             raise Http404(u"No %s available" % unicode(qs.model._meta.verbose_name_plural))
     215            raise Http404(_("No %(verbose_name_plural)s available")
     216                    % {'verbose_name_plural': force_unicode(qs.model._meta.verbose_name_plural)})
    212217
    213218        return date_list
    214219
     
    458463        qs = self.get_queryset()
    459464
    460465        if not self.get_allow_future() and date > datetime.date.today():
    461             raise Http404("Future %s not available because %s.allow_future is False." % (
    462                 qs.model._meta.verbose_name_plural, self.__class__.__name__)
     466            raise Http404(_("Future %(verbose_name_plural)s are not available "
     467                            "because %(class_name)s.allow_future is False.") % (
     468                {'verbose_name_plural': force_unicode(qs.model._meta.verbose_name_plural),
     469                 'class_name': self.__class__.__name__})
    463470            )
    464471
    465472        # Filter down a queryset from self.queryset using the date from the
     
    491498    try:
    492499        return datetime.date(*time.strptime(datestr, format)[:3])
    493500    except ValueError:
    494         raise Http404(u"Invalid date string '%s' given format '%s'" % (datestr, format))
     501        raise Http404(_("Invalid date string '%(date)s' given format '%(format)s'")
     502                % {'date': datestr,
     503                   'format': format})
    495504
    496505
    497506def _month_bounds(date):
  • views/generic/detail.py

     
    44from django.http import Http404
    55from django.utils.encoding import smart_str
    66from django.views.generic.base import TemplateResponseMixin, View
     7from django.utils.translation import ugettext as _
     8from django.utils.encoding import force_unicode
    79
    810
    911class SingleObjectMixin(object):
     
    4042
    4143        # If none of those are defined, it's an error.
    4244        else:
    43             raise AttributeError(u"Generic detail view %s must be called with "
    44                                  u"either an object id or a slug."
     45            raise AttributeError(_("Generic detail view %s must be called with "
     46                                   "either an object id or a slug.")
    4547                                 % self.__class__.__name__)
    4648
    4749        try:
    4850            obj = queryset.get()
    4951        except ObjectDoesNotExist:
    50             raise Http404(u"No %s found matching the query" %
    51                           (queryset.model._meta.verbose_name))
     52            raise Http404(_("No %(verbose_name)s found matching the query") %
     53                          {'verbose_name': force_unicode(queryset.model._meta.verbose_name)})
    5254        return obj
    5355
    5456    def get_queryset(self):
     
    6062            if self.model:
    6163                return self.model._default_manager.all()
    6264            else:
    63                 raise ImproperlyConfigured(u"%(cls)s is missing a queryset. Define "
    64                                            u"%(cls)s.model, %(cls)s.queryset, or override "
    65                                            u"%(cls)s.get_object()." % {
     65                raise ImproperlyConfigured(_("%(cls)s is missing a queryset. Define "
     66                                             "%(cls)s.model, %(cls)s.queryset, or override "
     67                                             "%(cls)s.get_object().") % {
    6668                                                'cls': self.__class__.__name__
    6769                                        })
    6870        return self.queryset._clone()
  • views/generic/create_update.py

     
    33from django.http import Http404, HttpResponse, HttpResponseRedirect
    44from django.core.xheaders import populate_xheaders
    55from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
    6 from django.utils.translation import ugettext
     6from django.utils.translation import ugettext as _
    77from django.contrib.auth.views import redirect_to_login
    88from django.views.generic import GenericViewError
    99from django.contrib import messages
     10from django.utils.encoding import force_unicode
    1011
     12
    1113import warnings
    1214warnings.warn(
    1315    'Function-based generic views have been deprecated; use class-based views instead.',
     
    4850        class_name = model.__name__ + 'Form'
    4951        form_class = ModelFormMetaclass(class_name, (ModelForm,), {'Meta': Meta})
    5052        return model, form_class
    51     raise GenericViewError("Generic view must be called with either a model or"
    52                            " form_class argument.")
     53    raise GenericViewError(_("Generic view must be called with either a model"
     54                             " or form_class argument."))
    5355
    5456def redirect(post_save_redirect, obj):
    5557    """
     
    7072    elif hasattr(obj, 'get_absolute_url'):
    7173        return HttpResponseRedirect(obj.get_absolute_url())
    7274    else:
    73         raise ImproperlyConfigured(
     75        raise ImproperlyConfigured(_(
    7476            "No URL to redirect to.  Either pass a post_save_redirect"
    7577            " parameter to the generic view or define a get_absolute_url"
    76             " method on the Model.")
     78            " method on the Model."))
    7779
    7880def lookup_object(model, object_id, slug, slug_field):
    7981    """
     
    8890    elif slug and slug_field:
    8991        lookup_kwargs['%s__exact' % slug_field] = slug
    9092    else:
    91         raise GenericViewError(
     93        raise GenericViewError(_(
    9294            "Generic view must be called with either an object_id or a"
    93             " slug/slug_field.")
     95            " slug/slug_field."))
    9496    try:
    9597        return model.objects.get(**lookup_kwargs)
    9698    except ObjectDoesNotExist:
    97         raise Http404("No %s found for %s"
    98                       % (model._meta.verbose_name, lookup_kwargs))
     99        raise Http404(_("No %(verbose_name)s found for %(lookup_kwargs)s")
     100                      % {'verbose_name': force_unicode(model._meta.verbose_name),
     101                         'lookup_kwargs': lookup_kwargs})
    99102
    100103def create_object(request, model=None, template_name=None,
    101104        template_loader=loader, extra_context=None, post_save_redirect=None,
     
    118121        if form.is_valid():
    119122            new_object = form.save()
    120123
    121             msg = ugettext("The %(verbose_name)s was created successfully.") %\
     124            msg = _("The %(verbose_name)s was created successfully.") %\
    122125                                    {"verbose_name": model._meta.verbose_name}
    123126            messages.success(request, msg, fail_silently=True)
    124127            return redirect(post_save_redirect, new_object)
     
    161164        form = form_class(request.POST, request.FILES, instance=obj)
    162165        if form.is_valid():
    163166            obj = form.save()
    164             msg = ugettext("The %(verbose_name)s was updated successfully.") %\
     167            msg = _("The %(verbose_name)s was updated successfully.") %\
    165168                                    {"verbose_name": model._meta.verbose_name}
    166169            messages.success(request, msg, fail_silently=True)
    167170            return redirect(post_save_redirect, obj)
     
    204207
    205208    if request.method == 'POST':
    206209        obj.delete()
    207         msg = ugettext("The %(verbose_name)s was deleted.") %\
    208                                     {"verbose_name": model._meta.verbose_name}
     210        msg = _("The %(verbose_name)s was deleted.") %\
     211                {"verbose_name": model._meta.verbose_name}
    209212        messages.success(request, msg, fail_silently=True)
    210213        return HttpResponseRedirect(post_delete_redirect)
    211214    else:
  • views/generic/edit.py

     
    44from django.views.generic.base import TemplateResponseMixin, View
    55from django.views.generic.detail import (SingleObjectMixin,
    66                        SingleObjectTemplateResponseMixin, BaseDetailView)
     7from django.utils.translation import ugettext as _
    78
    89
    910class FormMixin(object):
     
    5354            url = self.success_url
    5455        else:
    5556            raise ImproperlyConfigured(
    56                 "No URL to redirect to. Provide a success_url.")
     57                _("No URL to redirect to. Provide a success_url."))
    5758        return url
    5859
    5960    def form_valid(self, form):
     
    9394            try:
    9495                url = self.object.get_absolute_url()
    9596            except AttributeError:
    96                 raise ImproperlyConfigured(
     97                raise ImproperlyConfigured(_(
    9798                    "No URL to redirect to.  Either provide a url or define"
    98                     " a get_absolute_url method on the Model.")
     99                    " a get_absolute_url method on the Model."))
    99100        return url
    100101
    101102    def form_valid(self, form):
     
    223224            return self.success_url
    224225        else:
    225226            raise ImproperlyConfigured(
    226                 "No URL to redirect to. Provide a success_url.")
     227                _("No URL to redirect to. Provide a success_url."))
    227228
    228229
    229230class BaseDeleteView(DeletionMixin, BaseDetailView):
Back to Top