Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django BooleanField as radio buttons at the Inlineadmin

I couldn't find a street way to do it.

like image 905
Kareem Hashem Avatar asked Nov 23 '25 15:11

Kareem Hashem


2 Answers

I couldn't find a street way to do it, so I make tweak with JavaScript to do it.

$(document).ready(function() {
  $(".field-current").live("click",function(){

    $action = $($(this).children()[0])
    current_state = $action.is(':checked');
    $('.field-current').each(function(index) {
      var $temp = $($(this).children()[0])
      $temp.val(false);  
      $temp.attr('checked', false);
    });

    var $current = $($(this).children()[0])
    if (current_state == "on" || current_state == true){  
      $current.val(true);
      $current.attr('checked', true);
    }else{
      $current.val(false);
      $current.attr('checked', false);
    }
  });
});

in the admin page add

class ArticleDetailsInlineAdmin(admin.TabularInline):
     ....
    fields     = ['current', 'slug','summary','mod_date']

class ArticleHeaderAdmin(admin.ModelAdmin):
    inlines = [ArticleDetailsInlineAdmin,]
    ......
    form = ArticleForm

class Media:
        js = ('js/admin-current-article.js')

by doing this the current field will act like radio button among the inlineadmin

like image 54
Kareem Hashem Avatar answered Nov 26 '25 19:11

Kareem Hashem


Try using the formfield_overrides property to change the widget used (it's available on InlineAdmin classes as well as ModelAdmin):

from django.forms.widgets import RadioSelect

class ArticleDetailsInlineAdmin(admin.TabularInline):
    ...
    fields = ['current', 'slug', 'summary', 'mod_date']
    formfield_overrides = {
            models.BooleanField: {'widget': RadioSelect},
        }

Note this will use radio buttons instead of checkboxes for all BooleanFields in ArticleDetailsInlineAdmin.

like image 24
Stu Cox Avatar answered Nov 26 '25 17:11

Stu Cox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!