Online boolean switch in the admin list

 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
-- urls.py
    (r'^admin/(?P<url>.*)/switch/$', 'project.app.views.switch' ),
    (r'^admin/', include('django.contrib.admin.urls')),

-- app/views.py
def switch(request,url=''):
    from django.db.models import get_model
    if request.user and request.user.is_authenticated() and request.user.is_
staff:
    try:
        app_label,model_name,object_id,field) = url.split('/')
        model = get_model(app_label,model_name)
        object = get_object_or_404( model, pk=object_id )
        setattr(object,field,getattr(object,field)==0)
        object.save()
    except: pass
    return HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))

-- app/models.py
def boolean_switch(field):
    def _f(self):
        v = getattr(self,field.name)
        return '<a href ="%d/%s/switch/"><img src="/media/img/admin/icon
-%s.gif" alt="%d"/></a>'%(self.id,field.name,('no','yes')[v],v)
    _f.short_description = field.verbose_name
    _f.allow_tags = True
    return _f

More like this

  1. Exists Filter OneToOneField in Admin by davidvaz 2 years, 5 months ago
  2. Switch template tag by adurdin 5 years, 8 months ago
  3. FieldLevelPermissionsAdmin by buriy 6 years, 7 months ago
  4. Initial values for new items in admin by RommeDeSerieux 4 years, 7 months ago
  5. True Unique Boolean Model Decorator by kunitoki 1 year, 11 months ago

Comments

brunobord (on November 5, 2007):

Using Django 0.96, "self.id" in boolean_switch returned "None", and the link URL was not correct.

I replaced it by self._get_pk_val() and it worked.

#

favo (on November 6, 2007):

One issue, we can't order by that field, although it's not a big issue for boolean.

#

mayh90 (on September 13, 2010):

TIP: do not forget to import get_object_or_404 from django.shortcuts or switch will not work and no exception will be raised.

#

(Forgotten your password?)