Jak111
Jak111

Reputation: 119

Django admin list change boolean value on click

models.py

class Event(models.Model):
    name = models.CharField(max_length=80, blank=False)
    description = models.TextField(blank=True)
    date = models.DateField(blank=True, null=True)
    locked = models.BooleanField(default=False)

admin.py

class EventAdmin(admin.ModelAdmin):
   list_display = ('name', 'date', 'locked')
   search_fields = ['name']
  ordering = ['date']

admin.site.register(Event, EventAdmin)

Is it possible to change "locked" by clicking on the icons in the admin list ? I've tried to add "list_editable = ['locked']", but then the red/green icons aren't visible.

Thanks for your help :)

Upvotes: 1

Views: 2625

Answers (3)

Marco Giuliani
Marco Giuliani

Reputation: 79

You can use

list_editable = ['locked']

in your ModelAdmin to display it as a checkbox and display the Save button!

Upvotes: 0

Ian Roberts
Ian Roberts

Reputation: 51

Okay, I understand. You can do this to make that work.

def is_locked(self, obj):
    yes_icon = '<img src="/static/admin/img/icon-yes.svg" alt="True">'
    no_icon = '<img src="/static/admin/img/icon-no.svg" alt="False">'

    obj.locked = not obj.locked
    obj.save()

    if obj.locked:
        return '<a href="">%s</a>' % yes_icon
    else:
        return '<a href="">%s</a>' % no_icon

is_locked.allow_tags = True
is_locked.short_description = 'Locked'

Upvotes: 4

Ian Roberts
Ian Roberts

Reputation: 51

By default in Django, the first name in the list will be the click through, so you can use 'locked' in this way.

list_display = ('locked', 'name', 'date')

Alternatively, you can use a custom field in the list view and append the link in there like this:

class EventAdmin(admin.ModelAdmin):
    list_display = ('name', 'date', 'is_locked')
    search_fields = ('name',)
    ordering = ('date',)

    def is_locked(self, obj):
        yes_icon = '<img src="/static/admin/img/icon-yes.svg" alt="True">'
        no_icon = '<img src="/static/admin/img/icon-no.svg" alt="False">'
        if obj.is_tracer:
            return '<a target="_blank" href="%s/change/">%s</a>' % (obj.pk, yes_icon)
        else:
            return '<a target="_blank" href="%s/change/">%s</a>' % (obj.pk, no_icon)

    is_locked.allow_tags = True
    is_locked.short_description = 'Locked'

and in your list view add:

list_display = ('name', 'date', 'is_locked')

Upvotes: 0

Related Questions