51
The django admin uses custom widgets for many of its fields. The way to override fields is to create a Form for use with the ModelAdmin object.
# forms.py
from django import forms
from django.contrib import admin
class ProductAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ProductAdminForm, self).__init__(*args, **kwargs)
self.fields['tags'].widget = admin.widgets.AdminTextareaWidget()
Then, in your ModelAdmin object, you specify the form:
from django.contrib import admin
from models import Product
from forms import ProductAdminForm
class ProductAdmin(admin.ModelAdmin):
form = ProductAdminForm
admin.site.register(Product, ProductAdmin)
You can also override the queryset at this time: to filter objects according to another field in the model, for instance (since limit_choices_to
cannot handle this)
43
You can override field widgets by extending the Meta
class of a ModelForm
since Django 1.2:
from django import forms
from django.contrib import admin
class ProductAdminForm(forms.ModelForm):
class Meta:
model = Product
fields = '__all__' # edit: django >= 1.8
widgets = {
'tags': admin.widgets.AdminTextareaWidget
}
class ProductAdmin(admin.ModelAdmin):
form = ProductAdminForm
https://docs.djangoproject.com/en/stable/topics/forms/modelforms/#overriding-the-default-fields
- [Django]-Django β How to rename a model field using South?
- [Django]-How to return a static HTML file as a response in Django?
- [Django]-Uncaught TypeError: $(β¦).datepicker is not a function(anonymous function)
7
For a specific field not a kind of fields I use:
Django 2.1.7
class ProjectAdminForm(forms.ModelForm):
class Meta:
model = Project
fields = '__all__'
widgets = {
'project_description': forms.Textarea(attrs={'cols': 98})
}
class ProjectAdmin(admin.ModelAdmin):
form = ProjectAdminForm
Thanks, @Murat Γorlu
- [Django]-ERROR: Could not build wheels for backports.zoneinfo, which is required to install pyproject.toml-based projects
- [Django]-Django 1.9: Field clashes with the field of non-existing field in parent model
- [Django]-A Better Django Admin ManyToMany Field Widget
3
Try to change your field like this:
class TagField(forms.CharField):
def __init__(self, *args, **kwargs):
self.widget = forms.TextInput(attrs={'class':'tag_field'})
super(TagField, self).__init__(*args, **kwargs)
This would allow to use the widget which comes from **kwargs
. Otherwise your field will always use form.TextInput
widget.
- [Django]-Django β Model graphic representation (ERD)
- [Django]-How does Django's nested Meta class work?
- [Django]-Embedding JSON objects in script tags