57👍
✅
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
- 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)
52👍
There is another way to do this that is, IMO much easier if you want every field of the same type to have the same widget. This is done by specifying a formfield_overrides to the ModelAdmin. For example:
from django.forms.widgets import Textarea
class MyModelAdmin(admin.ModelAdmin):
formfield_overrides = {
models.TextField: {'widget': Textarea},
}
More in the docs: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_overrides
- [Django]-Installing PIL with JPEG support on Mac OS X
- [Django]-Count frequency of values in pandas DataFrame column
- [Django]-Django Programming error column does not exist even after running migrations
15👍
Here is a more dynamic extension of mgPePe’s response:
class MyAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyAdminForm, self).__init__(*args, **kwargs)
self.fields['by_admin'].label = 'My new label'
self.fields['by_admin'].widget = forms.RadioSelect()
class Meta:
model = TagCat
class MyAdmin(admin.ModelAdmin):
fields = ['name', 'by_admin']
form = MyAdminForm
This way you get full control over the fields.
- [Django]-Profiling Django
- [Django]-Django rest framework lookup_field through OneToOneField
- [Django]-How do I use Django groups and permissions?
0👍
You can also override this in the Admin class via the get_form()
method.
class MyAdmin(admin.ModelAdmin):
fields = ['name', 'by_admin']
form = MyAdminForm
def get_form(self, request, obj=None, change=False, **kwargs):
form = super().get_form(request, obj, change, **kwargs)
form.base_fields["by_admin"].label = 'My new label'
form.base_fields["by_admin"].widget = forms.RadioSelect()
return form
- [Django]-Django tests – patch object in all tests
- [Django]-How to use permission_required decorators on django class-based views
- [Django]-Why would running scheduled tasks with Celery be preferable over crontab?
Source:stackexchange.com