Login

Online boolean switch in the admin list

Author:
sasha
Posted:
September 5, 2007
Language:
Python
Version:
.96
Score:
6 (after 6 ratings)

You can switch boolean fields in the admin without editing objects

Usage:

` class News(models.Model):

    # ...

    pub = models.BooleanField(_('publication'),default=True)

    # ...

    pub_switch = boolean_switch(pub)

    class Admin:

         list_display = ('id', 'pub_switch')

`

Thanks for svetlyak.

 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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 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.

#

Please login first before commenting.