Django

Code

Changeset 1675

Show
Ignore:
Timestamp:
12/15/05 17:26:04 (3 years ago)
Author:
rjwittams
Message:

Changes to get admin semi-working

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/branches/magic-removal/django/contrib/admin/templatetags/adminapplist.py

    r1663 r1675  
    1818            if has_module_perms: 
    1919                model_list = [] 
     20                #HACK 
     21                app_url = "/".join( [comp for comp in app.__name__.split('.') if comp != 'models' ]) 
    2022                for m in app._MODELS: 
    2123                    if m._meta.admin: 
     
    2931                        # Check whether user has any perm for this module. 
    3032                        # If so, add the module to the model_list. 
     33                         
     34                         
    3135                        if True in perms.values(): 
    3236                            model_list.append({ 
    3337                                'name': capfirst(m._meta.verbose_name_plural), 
    34                                 'admin_url': '%s/%s/' % (app_label, m._meta.module_name), 
     38                                'admin_url': '%s/%s/' % (app_url, m.__name__.lower()), 
    3539                                'perms': perms, 
    3640                            }) 
  • django/branches/magic-removal/django/contrib/admin/templatetags/admin_list.py

    r1631 r1675  
    191191#@register.inclusion_tag("admin/date_hierarchy") 
    192192def date_hierarchy(cl): 
    193     lookup_opts, params, lookup_params, lookup_mod = \ 
    194       cl.lookup_opts, cl.params, cl.lookup_params, cl.lookup_mod 
     193    lookup_opts, params, lookup_params, manager = \ 
     194      cl.lookup_opts, cl.params, cl.lookup_params, cl.manager 
    195195 
    196196    if lookup_opts.admin.date_hierarchy: 
     
    209209 
    210210        def get_dates(unit, params): 
    211             return getattr(lookup_mod, 'get_%s_list' % field_name)(unit, **params) 
     211            return getattr(manager, 'get_%s_list' % field_name)(unit, **params) 
    212212 
    213213        if year_lookup and month_lookup and day_lookup: 
  • django/branches/magic-removal/django/contrib/admin/urls/admin.py

    r1530 r1675  
    4949 
    5050urlpatterns += ( 
    51     # Metasystem admin pages 
    52     ('^(?P<app_label>[^/]+)/(?P<module_name>[^/]+)/$', 'django.contrib.admin.views.main.change_list'), 
    53     ('^(?P<app_label>[^/]+)/(?P<module_name>[^/]+)/add/$', 'django.contrib.admin.views.main.add_stage'), 
    54     ('^(?P<app_label>[^/]+)/(?P<module_name>[^/]+)/(?P<object_id>.+)/history/$', 'django.contrib.admin.views.main.history'), 
    55     ('^(?P<app_label>[^/]+)/(?P<module_name>[^/]+)/(?P<object_id>.+)/delete/$', 'django.contrib.admin.views.main.delete_stage'), 
    56     ('^(?P<app_label>[^/]+)/(?P<module_name>[^/]+)/(?P<object_id>.+)/$', 'django.contrib.admin.views.main.change_stage'), 
     51    ('^((?:[^/]+/)+?)add/$', 'django.contrib.admin.views.main.add_stage'), 
     52    ('^((?:[^/]+/)+?)([^/]+)/history/$', 'django.contrib.admin.views.main.history'), 
     53    ('^((?:[^/]+/)+?)([^/]+)/delete/$', 'django.contrib.admin.views.main.delete_stage'), 
     54    ('^((?:[^/]+/)+?)([^/]+)/change/$', 'django.contrib.admin.views.main.change_stage'), 
     55    ('^((?:[^/]+/)+?)$', 'django.contrib.admin.views.main.change_list' ), 
    5756) 
    5857urlpatterns = patterns('', *urlpatterns) 
  • django/branches/magic-removal/django/contrib/admin/views/main.py

    r1648 r1675  
    11# Generic admin views. 
     2from django.conf import settings 
    23from django.contrib.admin.views.decorators import staff_member_required 
    34from django.contrib.admin.filterspecs import FilterSpec 
     
    2223from django.utils.html import escape 
    2324import operator 
     25from itertools import izip 
    2426 
    2527# The system will display a "Show all" link only if the total result count 
     
    4244    "Helper function that returns a tuple of (module, opts), raising Http404 if necessary." 
    4345    try: 
    44         mod = models.get_module(app_label, module_name
     46        mod = models.get_app(app_label
    4547    except ImportError: 
    4648        raise Http404 # Invalid app or module name. Maybe it's not in INSTALLED_APPS. 
     
    5052    return mod, opts 
    5153 
     54def matches_app(mod, comps): 
     55    modcomps = mod.__name__.split('.')[:-1] #HACK: leave off 'models' 
     56    for c, mc in izip(comps, modcomps): 
     57        if c != mc: 
     58            return ([],False) 
     59    return (comps[len(modcomps):], True) 
     60 
     61def find_model(mod, remaining): 
     62   # print "finding ", mod, remaining 
     63    if len(remaining) == 0: 
     64       # print "no comps left" 
     65        raise Http404 
     66    if len(remaining) == 1: 
     67        if hasattr(mod, '_MODELS'): 
     68            name = remaining[0] 
     69            for model in mod._MODELS: 
     70                print "'%s'" % name, model 
     71                if model.__name__.lower() == name: 
     72                    return model 
     73            raise Http404 
     74        else: 
     75            raise Http404 
     76    else: 
     77        child = getattr(mod, remaining[0], None) 
     78       # print mod, remaining[0], child 
     79        if child: 
     80            return find_model(child, remaining[1:]) 
     81        else: 
     82            raise Http404 
     83 
     84def get_app_label(mod): 
     85    modcomps = mod.__name__.split('.') 
     86    return modcomps[-2] 
     87 
     88def get_model_and_app(path): 
     89    comps = path.split('/') 
     90    comps = comps[:-1] # remove '' after final / 
     91    for mod in models.get_installed_models():   
     92        remaining, matched =  matches_app(mod, comps) 
     93        if matched and len(remaining) > 0: 
     94           # print "matched ", mod  
     95           # print "left", remaining 
     96            return ( find_model(mod, remaining), get_app_label(mod) ) 
     97             
     98    raise Http404 # Couldn't find app 
     99 
    52100def index(request): 
    53101    return render_to_response('admin/index', {'title': _('Site administration')}, context_instance=Context(request)) 
     
    58106 
    59107class ChangeList(object): 
    60     def __init__(self, request, app_label, module_name): 
    61         self.get_modules_and_options(app_label, module_name, request) 
     108    def __init__(self, request, path): 
     109        self.resolve_model(path, request) 
    62110        self.get_search_parameters(request) 
    63111        self.get_ordering() 
     
    95143        return '?' + '&amp;'.join(['%s=%s' % (k, v) for k, v in p.items()]).replace(' ', '%20') 
    96144 
    97     def get_modules_and_options(self, app_label, module_name, request): 
    98         self.mod, self.opts = _get_mod_opts(app_label, module_name) 
    99         if not request.user.has_perm(app_label + '.' + self.opts.get_change_permission()): 
     145    def resolve_model(self, path, request): 
     146        self.model, self.app_label = get_model_and_app(path) 
     147        # _get_mod_opts(app_label, module_name) 
     148        self.opts = self.model._meta 
     149         
     150        if not request.user.has_perm(self.app_label + '.' + self.opts.get_change_permission()): 
    100151            raise PermissionDenied 
    101152 
    102         self.lookup_mod, self.lookup_opts = self.mod, self.opts 
     153        self.lookup_opts = self.opts 
     154        self.manager = self.model._default_manager 
    103155 
    104156    def get_search_parameters(self, request): 
     
    115167 
    116168    def get_results(self, request): 
    117         lookup_mod, lookup_params, show_all, page_num = \ 
    118             self.lookup_mod, self.lookup_params, self.show_all, self.page_num 
     169        manager, lookup_params, show_all, page_num = \ 
     170            self.manager, self.lookup_params, self.show_all, self.page_num 
    119171        # Get the results. 
    120172        try: 
    121             paginator = ObjectPaginator(lookup_mod, lookup_params, DEFAULT_RESULTS_PER_PAGE) 
     173            paginator = ObjectPaginator(manager, lookup_params, DEFAULT_RESULTS_PER_PAGE) 
    122174        # Naked except! Because we don't have any other way of validating "params". 
    123175        # They might be invalid if the keyword arguments are incorrect, or if the 
     
    131183        del real_lookup_params['order_by'] 
    132184        if real_lookup_params: 
    133             full_result_count = lookup_mod.get_count() 
     185            full_result_count = manager.get_count() 
    134186        else: 
    135187            full_result_count = paginator.hits 
     
    141193        # Get the list of objects to display on this page. 
    142194        if (show_all and can_show_all) or not multi_page: 
    143             result_list = lookup_mod.get_list(**lookup_params) 
     195            result_list = manager.get_list(**lookup_params) 
    144196        else: 
    145197            try: 
     
    232284        self.lookup_params = lookup_params 
    233285 
    234 def change_list(request, app_label, module_name): 
     286def change_list(request, path): 
     287    print "change_list:", path 
    235288    try: 
    236         cl = ChangeList(request, app_label, module_name
     289        cl = ChangeList(request, path
    237290    except IncorrectLookupParameters: 
    238291        return HttpResponseRedirect(request.path) 
     
    243296        'cl' : cl 
    244297    }) 
    245     c.update({'has_add_permission': c['perms'][app_label][cl.opts.get_add_permission()]}), 
    246     return render_to_response(['admin/%s/%s/change_list' % (app_label, cl.opts.object_name.lower()), 
    247                                'admin/%s/change_list' % app_label, 
     298    c.update({'has_add_permission': c['perms'][cl.app_label][cl.opts.get_add_permission()]}), 
     299    return render_to_response(['admin/%s/%s/change_list' % (cl.app_label, cl.opts.object_name.lower()), 
     300                               'admin/%s/change_list' % cl.app_label, 
    248301                               'admin/change_list'], context_instance=c) 
    249302change_list = staff_member_required(change_list) 
     
    465518    LogEntry.objects.log_action(user.id, opts.get_content_type_id(), pk_value, str(new_object), CHANGE, change_message) 
    466519 
    467 def change_stage(request, app_label, module_name, object_id): 
    468     mod, opts = _get_mod_opts(app_label, module_name) 
     520def change_stage(request, path, object_id): 
     521    print "change_stage", path, object_id 
     522    model, app_label = get_model_and_app(path) 
     523    opts = model._meta 
     524    #mod, opts = _get_mod_opts(app_label, module_name) 
    469525    if not request.user.has_perm(app_label + '.' + opts.get_change_permission()): 
    470526        raise PermissionDenied 
    471527    if request.POST and request.POST.has_key("_saveasnew"): 
    472         return add_stage(request, app_label, module_name, form_url='../add/') 
     528        return add_stage(request, path, form_url='../add/') 
    473529    try: 
    474530        manipulator = mod.ChangeManipulator(object_id) 
  • django/branches/magic-removal/django/core/paginator.py

    r291 r1675  
    11from copy import copy 
    22from math import ceil 
     3from django.db.models import ModelBase 
    34 
    45class InvalidPage(Exception): 
     
    78class ObjectPaginator: 
    89    """ 
    9     This class makes pagination easy. Feed it a module (an object with 
    10     get_count() and get_list() methods) and a dictionary of arguments 
    11     to be passed to those methods, plus the number of objects you want 
    12     on each page. Then read the hits and pages properties to see how 
    13     many pages it involves. Call get_page with a page number (starting 
    14     at 0) to get back a list of objects for that page. 
    15  
     10    This class makes pagination easy. Feed it a manager (an object with 
     11    get_count() and get_list() methods) or a model which has a default manager, 
     12    and a dictionary of arguments to be passed to those methods, plus the  
     13    number of objects you want on each page. Then read the hits and pages  
     14    properties to see how many pages it involves. Call get_page with a page  
     15    number (starting at 0) to get back a list of objects for that page. 
     16     
    1617    Finally, check if a page number has a next/prev page using 
    1718    has_next_page(page_number) and has_previous_page(page_number). 
    1819    """ 
    19     def __init__(self, module, args, num_per_page, count_method='get_count', list_method='get_list'): 
    20         self.module, self.args = module, args 
     20    def __init__(self, manager_or_model, args, num_per_page, count_method='get_count', list_method='get_list'): 
     21        if hasattr(manager_or_model, '_default_manager'): 
     22            manager = manager_or_model._default_manager 
     23        else: 
     24            manager = manager_or_model 
     25        self.manager, self.args = manager, args 
    2126        self.num_per_page = num_per_page 
    2227        self.count_method, self.list_method = count_method, list_method 
     
    3641        # record to determine whether there's a next page. 
    3742        args['limit'] = self.num_per_page + 1 
    38         object_list = getattr(self.module, self.list_method)(**args) 
     43        object_list = getattr(self.manager, self.list_method)(**args) 
    3944        if not object_list: 
    4045            raise InvalidPage 
     
    4954                args['offset'] = (page_number + 1) * self.num_per_page 
    5055                args['limit'] = 1 
    51                 object_list = getattr(self.module, self.list_method)(**args) 
     56                object_list = getattr(self.manager, self.list_method)(**args) 
    5257                self._has_next[page_number] = (object_list != []) 
    5358            else: 
     
    6570            if order_args.has_key('select_related'): 
    6671                del order_args['select_related'] 
    67             self._hits = getattr(self.module, self.count_method)(**order_args) 
     72            self._hits = getattr(self.manager, self.count_method)(**order_args) 
    6873        return self._hits 
    6974 
  • django/branches/magic-removal/django/db/models/__init__.py

    r1672 r1675  
    10521052    delete.alters_data = True 
    10531053 
     1054    def __get_add_manipulator(cls): 
     1055        cls.AddManipulator = get_manipulator 
     1056         
     1057    AddManipulator = property(classmethod(__get_add_manipulator)) 
     1058     
     1059    def __get_change_manipulator(cls): 
     1060         
     1061    ChangeManipulator = property(classmethod(__get_change_manipulator))  
     1062     
     1063     
     1064 
    10541065    def __get_FIELD_display(self, field): 
    10551066        value = getattr(self, field.attname) 
     
    12581269        cursor.executemany(sql, [(this_id, i) for i in id_list]) 
    12591270        connection.commit() 
     1271 
     1272 
    12601273 
    12611274 
     
    15041517    return man 
    15051518 
     1519class AutomaticManipulator(formfields.Manipulator): 
     1520    def __classinit__(cls, model): 
     1521        cls.model = model 
     1522        cls.manager = model._default_manager 
     1523    __classinit__ = classmethod(__classinit__) 
     1524     
     1525    def __init__(self, follow=None): 
     1526        self.follow = self.model._meta.get_follow(follow) 
     1527        self.fields = [] 
     1528 
     1529        for f in opts.fields + opts.many_to_many: 
     1530            if self.follow.get(f.name, False): 
     1531                self.fields.extend(f.get_manipulator_fields(opts, self, change)) 
     1532     
     1533        # Add fields for related objects. 
     1534        for f in opts.get_all_related_objects(): 
     1535            if self.follow.get(f.name, False): 
     1536                fol = self.follow[f.name] 
     1537                self.fields.extend(f.get_manipulator_fields(opts, self, change, fol)) 
     1538         
     1539    def save(self): 
     1540        pass 
     1541     
     1542    def get_related_objects(opts, klass, add, change, self): 
     1543        return opts.get_followed_related_objects(self.follow) 
     1544 
     1545    def flatten_data(opts, klass, add, change, self): 
     1546         new_data = {} 
     1547         obj = change and self.original_object or None 
     1548         for f in opts.get_data_holders(self.follow): 
     1549            fol = self.follow.get(f.name) 
     1550            new_data.update(f.flatten_data(fol, obj)) 
     1551         return new_data 
     1552 
     1553class ModelAddManipulator(AutomaticManipulator): 
     1554    pass 
     1555 
     1556class ModelSaveManipulator(AutomaticManipulator): 
     1557    def __init__(self, obj_key=None, follow=None): 
     1558        
     1559        assert obj_key is not None, "ChangeManipulator.__init__() must be passed obj_key parameter." 
     1560        self.obj_key = obj_key 
     1561        try: 
     1562            self.original_object = self.manager.get_object(pk=obj_key) 
     1563        except ObjectDoesNotExist: 
     1564            # If the object doesn't exist, this might be a manipulator for a 
     1565            # one-to-one related object that hasn't created its subobject yet. 
     1566            # For example, this might be a Restaurant for a Place that doesn't 
     1567            # yet have restaurant information. 
     1568            if opts.one_to_one_field: 
     1569                # Sanity check -- Make sure the "parent" object exists. 
     1570                # For example, make sure the Place exists for the Restaurant. 
     1571                # Let the ObjectDoesNotExist exception propogate up. 
     1572                lookup_kwargs = opts.one_to_one_field.rel.limit_choices_to 
     1573                lookup_kwargs['%s__exact' % opts.one_to_one_field.rel.field_name] = obj_key 
     1574                _ = opts.one_to_one_field.rel.to._meta.get_model_module().get_object(**lookup_kwargs) 
     1575                params = dict([(f.attname, f.get_default()) for f in opts.fields]) 
     1576                params[opts.pk.attname] = obj_key 
     1577                self.original_object = opts.get_model_module().Klass(**params) 
     1578            else: 
     1579                raise 
     1580         
     1581        super(ModelSaveManipulator, self).__init__(self, follow=follow) 
     1582         
     1583        if  opts.get_ordered_objects(): 
     1584            self.fields.append(formfields.CommaSeparatedIntegerField(field_name="order_")) 
     1585 
    15061586def manipulator_init(opts, add, change, self, obj_key=None, follow=None): 
    15071587    self.follow = opts.get_follow(follow) 
     
    16921772    return new_object 
    16931773 
    1694 def manipulator_get_related_objects(opts, klass, add, change, self): 
    1695     return opts.get_followed_related_objects(self.follow) 
    1696  
    1697 def manipulator_flatten_data(opts, klass, add, change, self): 
    1698      new_data = {} 
    1699      obj = change and self.original_object or None 
    1700      for f in opts.get_data_holders(self.follow): 
    1701         fol = self.follow.get(f.name) 
    1702         new_data.update(f.flatten_data(fol, obj)) 
    1703      return new_data 
     1774 
    17041775 
    17051776def manipulator_validator_unique_together(field_name_list, opts, self, field_data, all_data):