Django: Admin: changing the widget of the field in Admin

mgPePe picture mgPePe · Dec 2, 2010 · Viewed 33.4k times · Source

I have a model with a boolean value like that:

class TagCat(models.Model):
    by_admin = models.BooleanField(default=True) 

This appears as a checkbox in admin.

  1. How could I use this as a radio button in admin?
  2. Also, how do I make it be always with a certain selected value in admin?
  3. Also, I want the default value to be the opposite, when a non-admin user adds a TagCat. This field should be hidden from him.

Can someone tell me how to do this? Django documentation doesn't seem to go in such details.

Answer

mgPePe picture mgPePe · Dec 2, 2010

UPDATE 1: Code that gets me done with 1) (don't forget tot pass CHOICES to the BooleanField in the model)

from main.models import TagCat
from django.contrib import admin
from django import forms

class MyTagCatAdminForm(forms.ModelForm):
    class Meta:
        model = TagCat
            widgets = {
              'by_admin':forms.RadioSelect
            }
            fields = '__all__' # required for Django 3.x
    
class TagCatAdmin(admin.ModelAdmin):
    form = MyTagCatAdminForm


admin.site.register(TagCat, TagCatAdmin)

The radio buttons appear ugly and displaced, but at least, they work

  1. I solved with following info in MyModel.py:
BYADMIN_CHOICES = (
    (1, "Yes"),
    (0, "No"),
)

class TagCat(models.Model):
    by_admin = models.BooleanField(choices=BYADMIN_CHOICES,default=1)