Commits

Rajeesh Nair committed 88103bf

Fixed issue #5. (Refer bitbucket issues page).

Comments (0)

Files changed (6)

django_monitor/__init__.py

 __author__ = "Rajeesh Nair"
-__version__ = "0.2"
+__version__ = "0.2.1a"
 __copyright__ = "Copyright (c) 2011 Rajeesh"
 __license__ = "BSD"
 
     if not model_from_queue(model):
         signals.post_save.connect(save_handler, sender = model)
         signals.pre_delete.connect(delete_handler, sender = model)
-        registered_model = get_model(
-            model._meta.app_label, model._meta.object_name, False
-        )
+        try:
+            registered_model = get_model(
+                model._meta.app_label, model._meta.object_name, False, False
+            )
+        except TypeError:
+            # Django versions prior to 1.4 accept 3 params to get_model.
+            registered_model = get_model(
+                model._meta.app_label, model._meta.object_name, False
+            )
         add_fields(
             registered_model, manager_name, status_name,
             monitor_name, base_manager

django_monitor/admin.py

-
 from django.contrib.contenttypes.models import ContentType
 from django.contrib import admin
-from django.contrib.admin.filterspecs import FilterSpec
+
+try:
+    from django.contrib.admin.filterspecs import FilterSpec
+    USING_FILTERSPEC = True
+except ImportError:
+    # For recent versions of Django, FilterSpec is no longer in use.
+    USING_FILTERSPEC = False
+
 from django.shortcuts import render_to_response
 from django.utils.functional import update_wrapper
 from django.template import RequestContext
 )
 from django_monitor.models import MonitorEntry
 
-# Our objective is to place the custom monitor-filter on top
-FilterSpec.filter_specs.insert(
-    0, (lambda f: getattr(f, 'monitor_filter', False), MonitorFilter)
-)
+if USING_FILTERSPEC:
+   # Our objective is to place the custom monitor-filter on top
+    FilterSpec.filter_specs.insert(
+        0, (lambda f: getattr(f, 'monitor_filter', False), MonitorFilter)
+    )
+else:
+   MonitorFilter.register(
+       lambda f: getattr(f, 'monitor_filter', False), MonitorFilter, True
+   )
 
 
 class MEAdmin(admin.ModelAdmin):
     change_list_template = 'admin/django_monitor/monitorentry/change_list.html'
 
     def get_urls(self):
-        """ The only url allowed is that for changelist_view. """
+        """The only url allowed is that for changelist_view. """
         from django.conf.urls.defaults import patterns, url
 
         def wrap(view):
         return urlpatterns
 
     def has_add_permission(self, request, obj = None):
-        """ Returns False so that no add button is displayed in admin index"""
+        """Return False so that no add button is displayed in admin index"""
         return False
 
     def has_change_permission(self, request, obj = None):

django_monitor/filter.py

-from django.contrib.admin.filterspecs import ChoicesFilterSpec
+try:
+    from django.contrib.admin.filterspecs import ChoicesFilterSpec as CFilter
+    USING_FILTERSPEC = True
+except ImportError:
+    # In recent versions of Django, FilterSpec is no longer in use.
+    from django.contrib.admin.filters import ChoicesFieldListFilter as CFilter
+    USING_FILTERSPEC = False
+
 from django.utils.encoding import smart_unicode
 from django.utils.translation import ugettext_lazy as _
 from django_monitor.conf import STATUS_DICT
 
-class MonitorFilter(ChoicesFilterSpec):
-    """
-    A custom filterspec to enable filter by monitor-status.
-    Django development version has changes in store to break this!
-    """
+class MonitorFilter(CFilter):
+
+    """A custom list-filter to enable filtering by monitor-status."""
+
     def __init__(
-        self, f, request, params, model, model_admin, field_path = None
+        self, field, request, params, model, model_admin, field_path = None
     ):
-        ChoicesFilterSpec.__init__(
-            self, f, request, params, model, model_admin, field_path
-        )
+        """Extended to set lookup_kwarg & lookup_val."""
         self.lookup_kwarg = 'status'
         # usually, lookup_vals are extracted from request.GET. But we have
         # intentionally removed ``status`` from GET before.
         )
         self.lookup_val = status_matches[0] if status_matches else None
         self.lookup_choices = STATUS_DICT.keys()
+        super(CFilter, self).__init__(
+            field, request, params, model, model_admin, field_path
+        )
+        if not USING_FILTERSPEC:
+            # Django >= 1.4 expects title as an attribute, not a method.
+            self.title = _("Moderation status")
+
+    def expected_parameters(self):
+        """Return the list of expected parameters."""
+        return [self.lookup_kwarg]
         
     def choices(self, cl):
         yield {
                 'display': STATUS_DICT[val]
             }
 
+if USING_FILTERSPEC:
+    # The older FilterSpec classes require title as a method.
     def title(self):
-        """ The title displayed above the filter"""
+        """The title displayed above the filter. Only for django < 1.4."""
         return _("Moderation status")
+    MonitorFilter.title = title
 

django_monitor/tests/tests.py

         # model_admin allows user to view just 2 objects that belong to her.
         response = self.client.get('/admin/test_app/reader/', follow = True)
         self.assertEquals(response.status_code, 200)
-        result_count = len(response.context[-1]['cl'].result_list)
+        try:
+            result_count = len(response.context[-1]['cl'].result_list)
+        except KeyError:
+            # In Django 1.4, cl is a member of response.context itself.
+            result_count = len(response.context['cl'].result_list)
         self.assertEquals(result_count, 2)
         # Now is the time to test monitor_queue. Same result expected.
         response = self.client.get(

django_monitor/util.py

             print "Adding permission '%s'" % p
 
 def add_fields(cls, manager_name, status_name, monitor_name, base_manager):
-    """ Add additional fields like status to moderated models"""
+    """Add additional fields like status to moderated models"""
     # Inheriting from old manager
     if base_manager is None:
         if hasattr(cls, manager_name):
                 'NAME': 'test_dm.db'
             }
         },
+        'SITE_ID': 1,
         'MIDDLEWARE_CLASSES': MIDDLEWARES,
         'INSTALLED_APPS': apps,
         'STATIC_URL': '/static/',