Ticket #1164: manipulator_contexts.diff

File manipulator_contexts.diff, 14.2 KB (added by jkocherhans <jkocherhans@…>, 19 years ago)
  • django/contrib/admin/views/stages/add.py

     
    44from django.contrib.admin.views.stages.modify import render_change_form
    55from django.core import formfields, template
    66from django.core.extensions import DjangoContext as Context
     7from django.core.extensions import ManipulatorContext
    78from django.db import models
    89from django.utils.httpwrappers import HttpResponse, HttpResponseRedirect
    910from django.utils.text import capfirst, get_text_list
     
    2223
    2324    if not request.user.has_perm(app_label + '.' + opts.get_add_permission()):
    2425        raise PermissionDenied
    25     manipulator = model.AddManipulator()
     26    context = ManipulatorContext(model, request)
     27    manipulator = model.AddManipulator(context=context)
    2628    if request.POST:
    2729        new_data = request.POST.copy()
    2830        if opts.has_field_type(models.FileField):
  • django/contrib/admin/views/stages/change.py

     
    11from django.contrib.admin.views.main import get_model_and_app
    22from django.core import formfields, template
    33from django.core.extensions import DjangoContext as Context
     4from django.core.extensions import ManipulatorContext
    45from django.contrib.admin.views.stages.modify import render_change_form
    56from django.db import models
    67from django.utils.text import capfirst, get_text_list
     
    3637        raise PermissionDenied
    3738    if request.POST and request.POST.has_key("_saveasnew"):
    3839        return add_stage(request, path, form_url='../../add/')
     40    context = ManipulatorContext(model, request)
    3941   
    4042    try:
    41         manipulator = model.ChangeManipulator(object_id)
     43        manipulator = model.ChangeManipulator(object_id, context=context)
    4244    except ObjectDoesNotExist:
    4345        raise Http404
    4446
  • django/db/models/manipulators.py

     
    6262
    6363    name = property(_get_name)
    6464
     65# TODO: I don't like initializing the manipulator with the context, but it's
     66# easier than passing around the context to a bunch of different methods in
     67# the manipulator       
    6568class AutomaticManipulator(Manipulator, Naming):
    6669    def _prepare(cls, model):
    6770        cls.model = model
     
    8285        setattr(other_cls, name, ManipulatorDescriptor(name, cls))
    8386    contribute_to_class = classmethod(contribute_to_class)
    8487
    85     def __init__(self, original_object=None, follow=None, name_parts=() ):
     88    def __init__(self, original_object=None, follow=None, name_parts=(), context=None):
    8689        Naming.__init__(self, name_parts)
    8790        if name_parts == ():
    8891            self.follow = self.model._meta.get_follow(follow)
     
    9093            self.follow = follow
    9194        self.fields_, self.children = [], {}
    9295        self.original_object = original_object
     96        self.context = context
    9397        for f in self.opts.get_data_holders(self.follow):
    9498            fol = self.follow[f.name]
    95             fields,manipulators = f.get_fields_and_manipulators(self.opts, self, follow=fol)
     99            fields,manipulators = f.get_fields_and_manipulators(self.opts, self, follow=fol, context=self.context)
    96100
    97101            if fields != None:
    98102                self.fields_.extend(fields)
     
    145149                # Fields with auto_now_add should keep their original value in the change stage.
    146150                auto_now_add = self.change and getattr(f, 'auto_now_add', False)
    147151                if self.follow.get(f.name, None) and not auto_now_add:
    148                     param = f.get_manipulator_new_data(expanded_data)
     152                    param = f.get_manipulator_new_data(expanded_data, context=self.context)
    149153                else:
    150154                    param = self.get_original_value(f)
    151155            params[f.attname] = param
     
    280284class ModelAddManipulator(AutomaticManipulator):
    281285    change = False
    282286    add = True
    283     def __init__(self, follow=None, name_parts=()):
    284         super(ModelAddManipulator, self).__init__(follow=follow, name_parts=name_parts)
     287    def __init__(self, follow=None, name_parts=(), context=None):
     288        super(ModelAddManipulator, self).__init__(follow=follow, name_parts=name_parts, context=context)
    285289
    286290    def get_original_value(self, field):
    287291        return field.get_default()
     
    293297    change = True
    294298    add = False
    295299
    296     def __init__(self, obj_key=None, follow=None, name_parts=()):
     300    def __init__(self, obj_key=None, follow=None, name_parts=(), context=None):
    297301        assert obj_key is not None, "ChangeManipulator.__init__() must be passed obj_key parameter."
    298302        opts = self.model._meta
    299303        if isinstance(obj_key, self.model):
     
    321325                else:
    322326                    raise
    323327
    324         super(ModelChangeManipulator, self).__init__(original_object=original_object, follow=follow, name_parts=name_parts)
     328        super(ModelChangeManipulator, self).__init__(original_object=original_object, follow=follow, name_parts=name_parts, context=context)
    325329        #self.original_object = original_object
    326330
    327331        #if self.opts.get_ordered_objects():
     
    336340        return "<Automatic ChangeManipulator '%s' for %s:%r >" % (self.name_prefix, self.model.__name__, self.obj_key)
    337341
    338342class ManipulatorCollection(list, Naming):
    339     def __init__(self, model, follow, name_parts=()):
     343    def __init__(self, model, follow, name_parts=(), context=None):
    340344        Naming.__init__(self, name_parts)
    341345        self.model = model
    342346        self.follow = follow
     347        self.context = context
    343348        self._load()
    344349
    345350    def _get_list(self):
     
    349354        man_class = self.model.ChangeManipulator
    350355
    351356        for i,obj in enumerate(self._get_list()):
    352             self.append(man_class(obj,self.follow, self.name_parts + (str(i),)  ))
     357            self.append(man_class(obj, self.follow, self.name_parts + (str(i),), context=self.context))
    353358
    354359    def _save_child(self, manip, parent_key):
    355360        manip.save_from_update()
     
    438443            self.append(None)
    439444
    440445        prefix = '%s%s.' % (self.name_prefix, index )
    441         child_manip = man_class(self.follow, self.name_parts + ( str(index), )  )
     446        child_manip = man_class(self.follow, self.name_parts + (str(index),), context=self.context)
    442447
    443448        self[index] = child_manip
    444449        return child_manip
  • django/db/models/fields/__init__.py

     
    218218            field_objs = self.get_manipulator_field_objs()
    219219        return (field_objs,params)
    220220
    221     def get_fields_and_manipulators(self, opts, manipulator, follow ):
     221    def get_fields_and_manipulators(self, opts, manipulator, follow, context=None):
    222222        change = manipulator.change
    223223        rel = manipulator.name_prefix != ''
    224224        name_prefix = manipulator.name_prefix
     
    278278    def get_validator_unique_lookup_type(self):
    279279        return '%s__exact' % f.name
    280280
    281     def get_manipulator_new_data(self, new_data, rel=False):
     281    def get_manipulator_new_data(self, new_data, rel=False, context=None):
    282282        """
    283283        Given the full new_data dictionary (from the manipulator), returns this
    284284        field's data.
     
    329329    def bind(self, fieldmapping, original, bound_field_class=BoundField):
    330330        return bound_field_class(self, fieldmapping, original)
    331331
     332    def get_context_processors(self):
     333        return []
     334
    332335class AutoField(Field):
    333336    empty_strings_allowed = False
    334337    def __init__(self, *args, **kwargs):
     
    343346    def get_manipulator_field_objs(self):
    344347        return [formfields.HiddenField]
    345348
    346     def get_manipulator_new_data(self, new_data, rel=False):
     349    def get_manipulator_new_data(self, new_data, rel=False, context=None):
    347350        # Never going to be called
    348351        # Not in main change pages
    349352        # ignored in related context
    350353        if not rel:
    351354            return None
    352         return Field.get_manipulator_new_data(self, new_data, rel)
     355        return Field.get_manipulator_new_data(self, new_data, rel, context)
    353356
    354357    def contribute_to_class(self, cls, name):
    355358        if cls._meta.has_auto_field:
     
    440443    def get_manipulator_field_names(self, name_prefix):
    441444        return [name_prefix + self.name + '_date', name_prefix + self.name + '_time']
    442445
    443     def get_manipulator_new_data(self, new_data, rel=False):
     446    def get_manipulator_new_data(self, new_data, rel=False, context=None):
    444447        date_field, time_field = self.get_manipulator_field_names('')
    445448        #if rel:
    446449        #    d = new_data.get(date_field, [None])[0]
  • django/db/models/related.py

     
    11from django.db.models.manipulators import ManipulatorCollection
    22
    33class RelatedManipulatorCollection(ManipulatorCollection):
    4     def __init__(self,related, parent_name_parts , instance, follow):
     4    def __init__(self, related, parent_name_parts , instance, follow, context=None):
    55        name_parts = parent_name_parts + (related.var_name, )
    66        self.instance = instance
    77        self.related = related
    88        super(RelatedManipulatorCollection, self).__init__(
    9             related.model,follow,name_parts)
     9            related.model, follow, name_parts, context)
    1010       
    1111    def _save_child(self, manip, parent_key):
    1212        setattr(manip.original_object, self.related.field.attname, parent_key)
     
    9696    def __repr__(self):
    9797        return "<RelatedObject: %s related to %s>" % (self.name, self.field.name)
    9898
    99     def get_fields_and_manipulators(self, opts, manipulator, follow ):
    100         return ([], self.get_manipulators(manipulator, follow)  )
     99    def get_fields_and_manipulators(self, opts, manipulator, follow, context=None):
     100        return ([], self.get_manipulators(manipulator, follow, context)  )
    101101
    102     def get_manipulators(self,parent_manipulator, follow):
     102    def get_manipulators(self, parent_manipulator, follow, context=None):
    103103        name_parts = parent_manipulator.name_parts
    104104        obj = parent_manipulator.original_object
    105105       
    106         return RelatedManipulatorCollection(self, name_parts, obj, follow)
     106        return RelatedManipulatorCollection(self, name_parts, obj, follow, context)
    107107
    108108    def bind(self, field_mapping, original, bound_related_object_class=BoundRelatedObject):
    109109        return bound_related_object_class(self, field_mapping, original)
  • django/core/extensions.py

     
    6262        for processor in get_standard_processors() + processors:
    6363            self.update(processor(request))
    6464
     65# TODO: should this really be a subclass of template.Context? It should
     66# (mostly) behave the same, but really has nothing to do with the template
     67# system. Maybe template.Context ought to be moved to just django.core.Context
     68class ManipulatorContext(Context):
     69    """
     70    This subclass of template.Context automatically populates itself using
     71    the processors defined in each field's get_context_processors method.
     72    Additional processors can be specified as a list of callables
     73    using the "processors" keyword argument.
     74    """
     75    def __init__(self, model, request, dict=None, processors=None):
     76        Context.__init__(self, dict)
     77
     78        standard_processors = []
     79        # Get all the processors from the fields in this model.
     80        for f in model._meta.fields:
     81            field_context_processors = f.get_context_processors()
     82            standard_processors.extend(field_context_processors)
     83        standard_processors = tuple(standard_processors)
     84        if processors is None:
     85            processors = ()
     86        else:
     87            processors = tuple(processors)
     88        for processor in standard_processors + processors:
     89            self.update(processor(request))
     90
     91
     92
    6593# PermWrapper and PermLookupDict proxy the permissions system into objects that
    6694# the template system can understand.
    6795
  • django/views/generic/create_update.py

     
    33from django.core.template import loader
    44from django.core import formfields, meta
    55from django.views.auth.login import redirect_to_login
    6 from django.core.extensions import DjangoContext
     6from django.core.extensions import DjangoContext, ManipulatorContext
    77from django.core.paginator import ObjectPaginator, InvalidPage
    88from django.utils.httpwrappers import HttpResponse, HttpResponseRedirect
    99from django.core.exceptions import Http404, ObjectDoesNotExist, ImproperlyConfigured
     
    2323        return redirect_to_login(request.path)
    2424
    2525    mod = models.get_module(app_label, module_name)
    26     manipulator = mod.AddManipulator(follow=follow)
     26    context = ManipulatorContext(mod, request)
     27    manipulator = model.AddManipulator(follow=follow, context=context)
    2728    if request.POST:
    2829        # If data was POSTed, we're trying to create a new object
    2930        new_data = request.POST.copy()
     
    8889        return redirect_to_login(request.path)
    8990
    9091    mod = models.get_module(app_label, module_name)
     92    context = ManipulatorContext(mod, request)
    9193
    9294    # Look up the object to be edited
    9395    lookup_kwargs = {}
     
    103105    except ObjectDoesNotExist:
    104106        raise Http404("%s.%s does not exist for %s" % (app_label, module_name, lookup_kwargs))
    105107
    106     manipulator = mod.ChangeManipulator(object.id, follow=follow)
     108    manipulator = mod.ChangeManipulator(object.id, follow=follow, context=context)
    107109
    108110    if request.POST:
    109111        new_data = request.POST.copy()
Back to Top