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.
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.
The way to override fields is to create a Form for use with the ModelAdmin object. This didn't work for me, you need to pass an instance of the widget, rather than the class. The instance worked perfectly, though. I typically would create custom admin forms in the admin.py and not mix them in with forms.py.
A widget is Django's representation of an HTML input element. The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget. The HTML generated by the built-in widgets uses HTML5 syntax, targeting <!
Overview. The Django admin application can use your models to automatically build a site area that you can use to create, view, update, and delete records. This can save you a lot of time during development, making it very easy to test your models and get a feel for whether you have the right data.
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
BYADMIN_CHOICES = ( (1, "Yes"), (0, "No"), ) class TagCat(models.Model): by_admin = models.BooleanField(choices=BYADMIN_CHOICES,default=1)
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:
class MyModelAdmin(admin.ModelAdmin): formfield_overrides = { models.TextField: {'widget': RichTextEditorWidget}, }
More in the docs: https://docs.djangoproject.com/en/1.4/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_overrides
UPDATED: Link to Django 2.0 version: https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_overrides
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With