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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
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.
#
One issue, we can't order by that field, although it's not a big issue for boolean.
#
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.