Login

ExtendibleModelAdminMixin

Author:
dokterbob
Posted:
November 17, 2009
Language:
Python
Version:
1.1
Tags:
admin extending extendible custum-views
Score:
3 (after 3 ratings)

A generic base class for extending ModelAdmin views. This can be used likewise:

def myview(self, request, object_id):
    obj = self._getobj(request, object_id)
    < do something >

def get_urls(self):
    urls = super(MyAdmin, self).get_urls()

    my_urls = patterns('',
        url(r'^(.+)/myview/$', 
            self._wrap(self.myview), 
            name=self._view_name('myview')),
        )

    return my_urls + urls
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from django.http import Http404

from functools import update_wrapper
from django.utils.translation import ugettext_lazy as _

from django.contrib.admin.util import unquote
from django.utils.encoding import force_unicode


class ExtendibleModelAdminMixin(object):
    def _getobj(self, request, object_id):
            opts = self.model._meta

            try:
                obj = self.queryset(request).get(pk=unquote(object_id))
            except self.model.DoesNotExist:
                # Don't raise Http404 just yet, because we haven't checked
                # permissions yet. We don't want an unauthenticated user to
                # be able to determine whether a given object exists.
                obj = None

            if obj is None:
                raise Http404(
                    _(
                        '%(name)s object with primary key '
                        '%(key)r does not exist.'
                    ) % {
                        'name': force_unicode(opts.verbose_name),
                        'key': unicode(object_id)
                    }
                )

            return obj

    def _wrap(self, view):
        def wrapper(*args, **kwargs):
            return self.admin_site.admin_view(view)(*args, **kwargs)
        return update_wrapper(wrapper, view)

    def _view_name(self, name):
        info = self.model._meta.app_label, self.model._meta.module_name, name

        return '%s_%s_%s' % info

More like this

  1. Rails-like MVC Controllers for Django by sciyoshi 6 years, 8 months ago
  2. TemplateZipFile by fcurella 3 years, 7 months ago
  3. Delete View by alcides 7 years ago
  4. Decorating class-based views by lqc 3 years, 5 months ago
  5. Owner required decorator by polarbear 7 years ago

Comments

dokterbob (on June 30, 2010):

Added imports so it all works a little easier now.

#

Please login first before commenting.