Django Admin: Setting list_display conditionally - django

Is there any admin model method like get_list_display() or some way that I can have some conditions to set different list_display values?
class FooAdmin (model.ModelAdmin):
# ...
def get_list_display ():
if some_cond:
return ('field', 'tuple',)
return ('other', 'field', 'tuple',)

The ModelAdmin class has a method called get_list_display which takes request as a parameter, by default returning the list_display property of the class.
So you can do for example:
class ShowEFilter(SimpleListFilter):
""" A dummy filter which just adds a filter option to show the E column,
but doesn't modify the queryset.
"""
title = _("Show E column")
parameter_name = "show_e"
def lookups(self, request, model_admin):
return [
("yes", "Yes"),
]
def queryset(self, request, queryset):
return queryset
class SomeModelAdmin(admin.ModelAdmin):
list_display = (
"a",
"b",
"c",
"d",
"e"
)
list_filter = (
ShowEFilter,
)
def get_list_display(self, request):
""" Removes the E column unless "Yes" has been selected in the
dummy filter.
"""
list_display = list(self.list_display)
if request.GET.get("show_e", "no") != "yes":
list_display.remove("e")
return list_display

Have you tried making that a property?
class FooAdmin(admin.ModelAdmin):
#property
def list_display(self):
if some_cond:
return ('field','tuple')
return ('other','field','tuple')
I haven't but it may work.
I'm also fairly certain you could spell it:
class FooAdmin(admin.ModelAdmin):
if CONDITION:
list_display = ('field','tuple')
else:
list_display = ('other','field','tuple')
But this one would only run the check at the time the FooAdmin class is interpreted: but if you were basing the test on settings.SOME_VALUE, for instance, then it may work.
Note also that the self in the first example is the instance of the FooAdmin class, not Foo itself.

You want to override the changelist_view method of the admin.ModelAdmin class:
def changelist_view(self, request, extra_context=None):
# just in case you are having problems with carry over from previous
# iterations of the view, always SET the self.list_display instead of adding
# to it
if something:
self.list_display = ['action_checkbox'] + ['dynamic_field_1']
else:
self.list_display = ['action_checkbox'] + ['dynamic_field_2']
return super(MyModelAdminClass, self).changelist_view(request, extra_context)
The 'action_checkbox' is what django uses to know to display the checkbox on the left hand side for the action drop down, so make sure you include it in setting the self.list_display. As usual if you simply set list_display for the ModelAdmin class normally you don't need to include it.

Related

Django conditional admin list_editable

Is there anyway to make the list_editable optional on a per object bases? For example the readonly fields attribute has this option, which doesn't affect the changelist_view.
class MyAdmin(admin.ModelAdmin):
readonly_fields = ('foo',)
def get_readonly_fields(self, request, obj=None):
fields = super(MyAdmin, self).get_readonly_fields(request, obj=obj)
if obj.status == 'CLOSED':
return fields + ('bar',)
return fields
The same can be achieved for list_display and some other attributes. It seems there isn't a method 'get_list_editable_fields'.
I want some of the rows to be immutable obviously, but other than raising a vulgar error doesn't seem to work. I didn't find any documentation about the attribute either
Would it somehow be possible to render the widget via a list_display getter?
class MyAdmin(admin.ModelAdmin):
list_display = ('get_bar',)
list_editable = ('get_bar',)
def get_bar(self, obj):
return widget or str(obj.bar) # ???
get_bar.allow_tags = True
update using Alasdair's feedback:
def get_changelist_formset(self, request, **kwargs):
"""
Returns a FormSet class for use on the changelist page if list_editable
is used.
"""
# I run through this code for each row in the changelist, but there's nothing in kwargs, so I don't know how to use the instance as a guide to which fields should be in list_editable?
defaults = {
"formfield_callback": partial(self.formfield_for_dbfield, request=request),
}
defaults.update(kwargs)
return modelformset_factory(
self.model, self.get_changelist_form(request), extra=0,
fields=self.list_editable, **defaults
)
As you say, there is no get_list_editable method.
Try overriding the get_changelist_formset method. I think you'll need to duplicate the entire method, and change the list of fields passed to modelformset_factory.
As said, there is not get_list_editable method in the ModelAdmin class, but it is possible to implement it easily (tested on django==2.1):
class MyAdminClass(admin.ModelAdmin):
def get_list_editable(self, request):
"""
get_list_editable method implementation,
django ModelAdmin doesn't provide it.
"""
dynamically_editable_fields = ('name', 'published', )
return dynamically_editable_fields
def get_changelist_instance(self, request):
"""
override admin method and list_editable property value
with values returned by our custom method implementation.
"""
self.list_editable = self.get_list_editable(request)
return super(MyAdminClass, self).get_changelist_instance(request)
Also, you could override the changelist_view and do something like that:
def changelist_view(self, request, extra_context=None):
resp = super(CustomModelAdmin, self).changelist_view(request, extra_context)
if something:
resp.context_data['cl'].formset = None
return resp
A little late but I found a way.
Override the get_changelist_instance()
def get_changelist_instance(self, request):
if request.user.is_superuser:
self.list_editable = ('state',) # replace state with list of fields you wish to be editable
else:
self.list_editable = ()
return super().get_changelist_instance(request)
It is better than overriding "get_changelist_formset" because get_changelist_formset() only runs if you have set list_editable to atleast one field. Link to Documentation

A Category model which creates proxy models for related model admin

So I'm having a bit of trouble with trying to create a model that will define dynamic proxy models that manage a related model in the admin site. I know that sentence was confusing, so I'll just share my code instead.
models.py
class Cateogry(models.Model):
name = models.CharField(...)
class Tag(models.Model):
name = models.CharField(...)
category = models.ForeignKey(Cateogry)
What I want to achieve is that in the admin site, instead of having one ModelAdmin for the Tag model, for each category I will have a modeladmin for all related tags. I have achieved this using this answer. Say I have a category named A:
def create_modeladmin(modeladmin, model, name = None):
class Meta:
proxy = True
app_label = model._meta.app_label
attrs = {'__module__': '', 'Meta': Meta}
newmodel = type(name, (model,), attrs)
admin.site.register(newmodel, modeladmin)
return modeladmin
class CatA(TagAdmin):
def queryset(self, request):
qs = super(CatA, self).queryset(request)
return qs.filter(cateogry = Cateogry.objects.filter(name='A'))
create_modeladmin(CatA, name='CategoryAtags', model=Tag)
But this is not good enough, because obviously I still need to manually subclass the TagAdmin model and then run create_modeladmin. What I need to do, is loop over all Category objects, for each one create a dynamic subclass for Tagadmin (named after the category), then create a dynamic proxy model from that, and this is where my head starts spinning.
for cat in Category.objects.all():
NewSubClass = #somehow create subclass of TagAdmin, the name should be '<cat.name>Admin' instead of NewSubClass
create_modeladmin(NewSubClass, name=cat.name, model=Tag)
Any guidance or help would be much appreciated
Dynamic ModelAdmins don't work well together with the way admin registeres models.
I suggest to create subviews in the CategoryAdmin.
from django.conf.urls import patterns, url
from django.contrib import admin
from django.contrib.admin.options import csrf_protect_m
from django.contrib.admin.util import unquote
from django.core.urlresolvers import reverse
from demo_project.demo.models import Category, Tag
class TagAdmin(admin.ModelAdmin):
# as long as the CategoryTagAdmin class has no custom change_list template
# there needs to be a default admin for Tags
pass
admin.site.register(Tag, TagAdmin)
class CategoryTagAdmin(admin.ModelAdmin):
""" A ModelAdmin invoked by a CategoryAdmin"""
read_only_fields = ('category',)
def __init__(self, model, admin_site, category_admin, category_id):
self.model = model
self.admin_site = admin_site
self.category_admin = category_admin
self.category_id = category_id
super(CategoryTagAdmin, self).__init__(model, admin_site)
def queryset(self, request):
return super(CategoryTagAdmin, self).queryset(request).filter(category=self.category_id)
class CategoryAdmin(admin.ModelAdmin):
list_display = ('name', 'tag_changelist_link')
def tag_changelist_link(self, obj):
info = self.model._meta.app_label, self.model._meta.module_name
return '<a href="%s" >Tags</a>' % reverse('admin:%s_%s_taglist' % info, args=(obj.id,))
tag_changelist_link.allow_tags = True
tag_changelist_link.short_description = 'Tags'
#csrf_protect_m
def tag_changelist(self, request, *args, **kwargs):
obj_id = unquote(args[0])
info = self.model._meta.app_label, self.model._meta.module_name
category = self.get_object(request, obj_id)
tag_admin = CategoryTagAdmin(Tag, self.admin_site, self, category_id=obj_id )
extra_context = {
'parent': {
'has_change_permission': self.has_change_permission(request, obj_id),
'opts': self.model._meta,
'object': category,
},
}
return tag_admin.changelist_view(request, extra_context)
def get_urls(self):
info = self.model._meta.app_label, self.model._meta.module_name
urls= patterns('',
url(r'^(.+)/tags/$', self.admin_site.admin_view(self.tag_changelist), name='%s_%s_taglist' % info )
)
return urls + super(CategoryAdmin, self).get_urls()
admin.site.register(Category, CategoryAdmin)
The items in the categories changelist have an extra column with a link made by the tag_changelist_link pointing to the CategoryAdmin.tag_changelist. This method creates a CategoryTagAdmin instance with some extras and returns its changelist_view.
This way you have a filtered tag changelist on every category. To fix the breadcrumbs of the tag_changelist view you need to set the CategoryTagAdmin.change_list_template to a own template that {% extends 'admin/change_list.html' %} and overwrites the {% block breadcrumbs %}. That is where you will need the parent variable from the extra_context to create the correct urls.
If you plan to implement a tag_changeview and tag_addview method you need to make sure that the links rendered in variouse admin templates point to the right url (e.g. calling the change_view with a form_url as paramter).
A save_model method on the CategoryTagAdmin can set the default category when adding new tags.
def save_model(self, request, obj, form, change):
obj.category_id = self.category_id
super(CategoryTagAdmin, self).__init__(request, obj, form, change)
If you still want to stick to the apache restart aproach ... Yes you can restart Django. It depends on how you are deploying the instance.
On an apache you can touch the wsgi file that will reload the instance os.utime(path/to/wsgi.py.
When using uwsgi you can use uwsgi.reload().
You can check the source code of Rosetta how they are restarting the instance after the save translations (views.py).
So I found a half-solution.
def create_subclass(baseclass, name):
class Meta:
app_label = 'fun'
attrs = {'__module__': '', 'Meta': Meta, 'cat': name }
newsub = type(name, (baseclass,), attrs)
return newsub
class TagAdmin(admin.ModelAdmin):
list_display = ('name', 'category')
def get_queryset(self, request):
return Tag.objects.filter(category = Category.objects.filter(name=self.cat))
for cat in Category.objects.all():
newsub = create_subclass(TagAdmin, str(cat.name))
create_modeladmin(newsub, model=Tag, name=str(cat.name))
It's working. But every time you add a new category, you need to refresh the server before it shows up (because admin.py is evaluated at runtime). Does anyone know a decent solution to this?

How to override the queryset giving the filters in list_filter?

Given the following models
class AnotherModel(models.Model):
n = models.IntegerField()
class MyModel(models.Model):
somefield = models.ForeignKey(AnotherModel)
and admin
class MyModelAdmin(admin.ModelAdmin):
list_filter = ('somefield',)
how can I filter the instances of AnotherModel to show only those with a given n value in my admin filter?
I need something like:
Filter
By somefield
all
[list of AnotherModel instances with given n]
See ModelAdmin.queryset and ModelAdmin.formfield_for_foreignkey. From the docs:
The queryset method on a ModelAdmin returns a QuerySet of all model instances that can be edited by the admin site. One use case for overriding this method is to show objects owned by the logged-in user:
class MyModelAdmin(admin.ModelAdmin):
def queryset(self, request):
qs = super(MyModelAdmin, self).queryset(request)
if request.user.is_superuser:
return qs
return qs.filter(author=request.user)
The formfield_for_foreignkey method on a ModelAdmin allows you to override the default formfield for a foreign keys field. For example, to return a subset of objects for this foreign key field based on the user:
class MyModelAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "car":
kwargs["queryset"] = Car.objects.filter(owner=request.user)
return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
This uses the HttpRequest instance to filter the Car foreign key field to only display the cars owned by the User instance.
[update]
Sorry, I failed to read the "filter" part. In Django >= 1.4 you can pass a subclass of django.contrib.admin.SimpleListFilter in the list_filter argument list, which you can use in order to override the lookups and queryset methods.
from datetime import date
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
class DecadeBornListFilter(admin.SimpleListFilter):
# Human-readable title which will be displayed in the
# right admin sidebar just above the filter options.
title = _('decade born')
# Parameter for the filter that will be used in the URL query.
parameter_name = 'decade'
def lookups(self, request, model_admin):
"""
Returns a list of tuples. The first element in each
tuple is the coded value for the option that will
appear in the URL query. The second element is the
human-readable name for the option that will appear
in the right sidebar.
"""
return (
('80s', _('in the eighties')),
('90s', _('in the nineties')),
)
def queryset(self, request, queryset):
"""
Returns the filtered queryset based on the value
provided in the query string and retrievable via
`self.value()`.
"""
# Compare the requested value (either '80s' or '90s')
# to decide how to filter the queryset.
if self.value() == '80s':
return queryset.filter(birthday__gte=date(1980, 1, 1),
birthday__lte=date(1989, 12, 31))
if self.value() == '90s':
return queryset.filter(birthday__gte=date(1990, 1, 1),
birthday__lte=date(1999, 12, 31))
class PersonAdmin(admin.ModelAdmin):
list_filter = (DecadeBornListFilter,)
Edit - this method has been pointed out to have issues, see below
You can do it like this:
Let's say you have a model called Animal, which has a ForeignKey field to a model called Species. In a particular admin list, you want to allow only certain species to be shown in the animals filter choices.
First, specify a custom ListFilter called SpeciesFilter in the Animal's ModelAdmin:
class AnimalAdmin(ModelAdmin):
list_filter = (('species', SpeciesFilter),)
Then define the SpeciesFilter:
from django.contrib.admin.filters import RelatedFieldListFilter
class SpeciesFilter(RelatedFieldListFilter):
def __init__(self, field, request, *args, **kwargs):
"""Get the species you want to limit it to.
This could be determined by the request,
But in this example we'll just specify an
arbitrary species"""
species = Species.objects.get(name='Tarantula')
#Limit the choices on the field
field.rel.limit_choices_to = {'species': species}
#Let the RelatedFieldListFilter do its magic
super(SpeciesFilter, self).__init__(field, request, *args, **kwargs)
That should do it.
I found another method similar to #seddonym, but doesn't mess with the caching. It is based on this Django code, but uses undocumented method field_choices, which can be subject to change in the future Django releases. The code for #seddonym's case would be:
from django.contrib.admin.filters import RelatedFieldListFilter
class SpeciesFilter(RelatedFieldListFilter):
def field_choices(self, field, request, model_admin):
return field.get_choices(include_blank=False, limit_choices_to={'name': 'Tarantula'})
Or in my case the working code is:
from django.contrib.admin.filters import RelatedFieldListFilter
class UnitFilter(RelatedFieldListFilter):
def field_choices(self, field, request, model_admin):
return field.get_choices(include_blank=False, limit_choices_to={'pk__in': request.user.administrated_units.all()})
I had to create my lookup fields from db table. I created custom filter class as below and displaying only related values to logged in user and filter accordingly:
class ShiftFilter_Org(admin.SimpleListFilter):
title = 'Organisation'
parameter_name = 'org'
def lookups(self, request, model_admin):
"""Get the organisations you want to limit"""
qs_org = Organisation.objects.filter(users=request.user)
list_org = []
for og in qs_org:
list_org.append(
(og.id, og.name)
)
return (
sorted(list_org, key=lambda tp:tp[1])
)
def queryset(self, request, queryset):
if self.value():
return queryset.filter(org=self.value())
For more visit Getting the most out of Django Admin filters
To use RelatedFieldListFilter like suggested in some answers, you need to pass a tuple to list_filter. Following the classes definition used in the original question, you would have:
class MyModelAdmin(admin.ModelAdmin):
class AnotherModelListFilter(admin.RelatedFieldListFilter):
def field_choices(self, field, request, model_admin):
ordering = self.field_admin_ordering(field, request, model_admin)
return field.get_choices(
include_blank=False,
ordering=ordering,
limit_choices_to=dict(n=<THE_VALUE_YOU_WANT>),
)
list_filter = (('somefield', AnotherModelListFilter),)

Creating Custom Filters for list_filter in Django Admin

I would like to make custom filters for django admin instead of the normal 'is_staff' and 'is_superuser'. I have read this list_filter in Django docs.
Custom Filters work in this way:
from datetime import date
from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter
class DecadeBornListFilter(SimpleListFilter):
# Human-readable title which will be displayed in the
# right admin sidebar just above the filter options.
title = _('decade born')
# Parameter for the filter that will be used in the URL query.
parameter_name = 'decade'
def lookups(self, request, model_admin):
"""
Returns a list of tuples. The first element in each
tuple is the coded value for the option that will
appear in the URL query. The second element is the
human-readable name for the option that will appear
in the right sidebar.
"""
return (
('80s', _('in the eighties')),
('90s', _('in the nineties')),
)
def queryset(self, request, queryset):
"""
Returns the filtered queryset based on the value
provided in the query string and retrievable via
`self.value()`.
"""
# Compare the requested value (either '80s' or '90s')
# to decide how to filter the queryset.
if self.value() == '80s':
return queryset.filter(birthday__gte=date(1980, 1, 1),
birthday__lte=date(1989, 12, 31))
if self.value() == '90s':
return queryset.filter(birthday__gte=date(1990, 1, 1),
birthday__lte=date(1999, 12, 31))
class PersonAdmin(ModelAdmin):
list_filter = (DecadeBornListFilter,)
But i have already made custom functions for list_display like this:
def Student_Country(self, obj):
return '%s' % obj.country
Student_Country.short_description = 'Student-Country'
Is it possible i could use the custom functions for list_display in list_filter instead of writing a new custom function for list_filter? Any suggestions or improvements are welcome.. Need some guidance on this... Thanks...
You can indeed add custom filters to admin filters by extending SimpleListFilter. For instance, if you want to add a continent filter for 'Africa' to the country admin filter used above, you can do the following:
In admin.py:
from django.contrib.admin import SimpleListFilter
class CountryFilter(SimpleListFilter):
title = 'country' # or use _('country') for translated title
parameter_name = 'country'
def lookups(self, request, model_admin):
countries = set([c.country for c in model_admin.model.objects.all()])
return [(c.id, c.name) for c in countries] + [
('AFRICA', 'AFRICA - ALL')]
def queryset(self, request, queryset):
if self.value() == 'AFRICA':
return queryset.filter(country__continent='Africa')
if self.value():
return queryset.filter(country__id__exact=self.value())
class CityAdmin(ModelAdmin):
list_filter = (CountryFilter,)
Your list_display ,method returns a string, but if I understand correctly, what you want to do is add a filter which allows selection of countries of students, correct?
For this simple relation filter, and in fact for the "Student-Country" list display column as well, you don't need to create a custom filter class, nor a custom list display method; this would suffice:
class MyAdmin(admin.ModelAdmin):
list_display = ('country', )
list_filter = ('country', )
The way django does list_filter, as explained in the docs, is first by automatically matching fields you provide to pre-built filter classes; these filters include CharField and ForeignKey.
list_display similarly automates the population of the changelist column using the field passed by retrieving the related objects and returning the unicode value of these (same as in the method you provided above).
In addition to Rick Westera answer, here is the Django Docs for this situation
ModelAdmin.list_filter
Set list_filter to activate filters in the right sidebar of the change list page of the admin
list_filter should be a list or tuple of elements
the lookup function is that show the exists values in admin;
in queryset function, self.value() is that was filtering by..
from django.contrib.admin import SimpleListFilter
class AllPriceFilter(admin.SimpleListFilter):
title = 'All Price'
parameter_name = 'All Price'
def lookups(self, request, model_admin):
return [(i.all_price, i.all_price) for i in model_admin.model.objects.all()]
def queryset(self, request, queryset):
if self.value():
return queryset.filter(all_price__lte=self.value())
class MyAdmin(admin.ModelAdmin):
list_filter = (AllPriceFilter, )

Dynamic fields in Django Admin

I want to have additional fields regarding value of one field. Therefor I build a custom admin form to add some new fields.
Related to the blogpost of jacobian 1 this is what I came up with:
class ProductAdminForm(forms.ModelForm):
class Meta:
model = Product
def __init__(self, *args, **kwargs):
super(ProductAdminForm, self).__init__(*args, **kwargs)
self.fields['foo'] = forms.IntegerField(label="foo")
class ProductAdmin(admin.ModelAdmin):
form = ProductAdminForm
admin.site.register(Product, ProductAdmin)
But the additional field 'foo' does not show up in the admin. If I add the field like this, all works fine but is not as dynamic as required, to add the fields regarding the value of another field of the model
class ProductAdminForm(forms.ModelForm):
foo = forms.IntegerField(label="foo")
class Meta:
model = Product
class ProductAdmin(admin.ModelAdmin):
form = ProductAdminForm
admin.site.register(Product, ProductAdmin)
So is there any initialize method that i have to trigger again to make the new field working? Or is there any other attempt?
Here is a solution to the problem. Thanks to koniiiik i tried to solve this by extending the *get_fieldsets* method
class ProductAdmin(admin.ModelAdmin):
def get_fieldsets(self, request, obj=None):
fieldsets = super(ProductAdmin, self).get_fieldsets(request, obj)
fieldsets[0][1]['fields'] += ['foo']
return fieldsets
If you use multiple fieldsets be sure to add the to the right fieldset by using the appropriate index.
The accepted answer above worked in older versions of django, and that's how I was doing it. This has now broken in later django versions (I am on 1.68 at the moment, but even that is old now).
The reason it is now broken is because any fields within fieldsets you return from ModelAdmin.get_fieldsets() are ultimately passed as the fields=parameter to modelform_factory(), which will give you an error because the fields on your list do not exist (and will not exist until your form is instantiated and its __init__ is called).
In order to fix this, we must override ModelAdmin.get_form() and supply a list of fields that does not include any extra fields that will be added later. The default behavior of get_form is to call get_fieldsets() for this information, and we must prevent that from happening:
# CHOOSE ONE
# newer versions of django use this
from django.contrib.admin.utils import flatten_fieldsets
# if above does not work, use this
from django.contrib.admin.util import flatten_fieldsets
class MyModelForm(ModelForm):
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
# add your dynamic fields here..
for fieldname in ('foo', 'bar', 'baz',):
self.fields[fieldname] = form.CharField()
class MyAdmin(ModelAdmin):
form = MyModelForm
fieldsets = [
# here you put the list of fieldsets you want displayed.. only
# including the ones that are not dynamic
]
def get_form(self, request, obj=None, **kwargs):
# By passing 'fields', we prevent ModelAdmin.get_form from
# looking up the fields itself by calling self.get_fieldsets()
# If you do not do this you will get an error from
# modelform_factory complaining about non-existent fields.
# use this line only for django before 1.9 (but after 1.5??)
kwargs['fields'] = flatten_fieldsets(self.declared_fieldsets)
# use this line only for django 1.9 and later
kwargs['fields'] = flatten_fieldsets(self.fieldsets)
return super(MyAdmin, self).get_form(request, obj, **kwargs)
def get_fieldsets(self, request, obj=None):
fieldsets = super(MyAdmin, self).get_fieldsets(request, obj)
newfieldsets = list(fieldsets)
fields = ['foo', 'bar', 'baz']
newfieldsets.append(['Dynamic Fields', { 'fields': fields }])
return newfieldsets
This works for adding dynamic fields in Django 1.9.3, using just a ModelAdmin class (no ModelForm) and by overriding get_fields. I don't know yet how robust it is:
class MyModelAdmin(admin.ModelAdmin):
fields = [('title','status', ), 'description', 'contact_person',]
exclude = ['material']
def get_fields(self, request, obj=None):
gf = super(MyModelAdmin, self).get_fields(request, obj)
new_dynamic_fields = [
('test1', forms.CharField()),
('test2', forms.ModelMultipleChoiceField(MyModel.objects.all(), widget=forms.CheckboxSelectMultiple)),
]
#without updating get_fields, the admin form will display w/o any new fields
#without updating base_fields or declared_fields, django will throw an error: django.core.exceptions.FieldError: Unknown field(s) (test) specified for MyModel. Check fields/fieldsets/exclude attributes of class MyModelAdmin.
for f in new_dynamic_fields:
#`gf.append(f[0])` results in multiple instances of the new fields
gf = gf + [f[0]]
#updating base_fields seems to have the same effect
self.form.declared_fields.update({f[0]:f[1]})
return gf
Maybe I am a bit late... However, I am using Django 3.0 and also wanted to dynamically ad some custom fields to the form, depending on the request.
I end up with a solution similar to the one described by #tehfink combined with #little_birdie.
However, just updating self.form.declared_fields as suggested didn't help. The result of this procedure is, that the list of custom fields defined in self.form.declared_fields always grows from request to request.
I solved this by initialising this dictionary first:
class ModelAdminGetCustomFieldsMixin(object):
def get_fields(self, request, obj=None):
fields = super().get_fields(request, obj=None)
self.form.declared_fields = {}
if obj:
for custom_attribute in custom_attribute_list:
self.form.declared_fields.update({custom_attribute.name: custom_attribute.field})
return fields
where custom_attribute.field is a form field instance.
Additionally, it was required to define a ModelForm, wherein during initialisation the custom fields have been added dynamically as well:
class SomeModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for custom_attribute in custom_attribute_list:
self.fields[custom_attribute.name] = custom_attribute.field
and use this ModelForm in the ModelAdmin.
Afterwards, the newly defined attributes can be used in, e.g., a fieldset.
While Jacob's post might work all right for regular ModelForms (even though it's more than a year and a half old), the admin is a somewhat different matter.
All the declarative way of defining models, forms ModelAdmins and whatnot makes heavy use of metaclasses and class introspection. Same with the admin – when you tell a ModelAdmin to use a specific form istead of creating a default one, it introspects the class. It gets the list of fields and other stuff from the class itself without instantiating it.
Your custom class, however, does not define the extra form field at class level, instead it dynamically adds one after it has been instantiated – that's too late for the ModelAdmin to recognize this change.
One way to go about your problem might be to subclass ModelAdmin and override its get_fieldsets method to actually instantiate the ModelForm class and get the list of fields from the instance instead of the class. You'll have to keep in mind, though, that this might be somewhat slower than the default implementation.
You can create dynamic fields and fieldset using the form meta class. Sample code is given below. Add the loop logic as per you requirements.
class CustomAdminFormMetaClass(ModelFormMetaclass):
"""
Metaclass for custom admin form with dynamic field
"""
def __new__(cls, name, bases, attrs):
for field in get_dynamic_fields: #add logic to get the fields
attrs[field] = forms.CharField(max_length=30) #add logic to the form field
return super(CustomAdminFormMetaClass, cls).__new__(cls, name, bases, attrs)
class CustomAdminForm(six.with_metaclass(CustomAdminFormMetaClass, forms.ModelForm)):
"""
Custom admin form
"""
class Meta:
model = ModelName
fields = "__all__"
class CustomAdmin(admin.ModelAdmin):
"""
Custom admin
"""
fieldsets = None
form = CustomAdminForm
def get_fieldsets(self, request, obj=None):
"""
Different fieldset for the admin form
"""
self.fieldsets = self.dynamic_fieldset(). #add logic to add the dynamic fieldset with fields
return super(CustomAdmin, self).get_fieldsets(request, obj)
def dynamic_fieldset(self):
"""
get the dynamic field sets
"""
fieldsets = []
for group in get_field_set_groups: #logic to get the field set group
fields = []
for field in get_group_fields: #logic to get the group fields
fields.append(field)
fieldset_values = {"fields": tuple(fields), "classes": ['collapse']}
fieldsets.append((group, fieldset_values))
fieldsets = tuple(fieldsets)
return fieldsets
Stephan's answer is elegant, but when I used in in dj1.6 it required the field to be a tuple.
The complete solution looked like this:
class ProductForm(ModelForm):
foo = CharField(label='foo')
class ProductAdmin(admin.ModelAdmin):
form = ProductForm
def get_fieldsets(self, request, obj=None):
fieldsets = super(ProductAdmin, self).get_fieldsets(request, obj)
fieldsets[0][1]['fields'] += ('foo', )
return fieldsets
not sure why that's not working, but could a possible workaround be to define the field statically (on the form) and then override it in the __init__?
I for a long time could not solve a problem with dynamic addition of fields.
The solution "little_birdie" really works. Thank you Birdie))
The only nuance is:
"Self.declared_fieldsets" should be replaced with "self.fieldsets".
#kwargs['fields'] = flatten_fieldsets(self.declared_fieldsets)
kwargs['fields'] = flatten_fieldsets(self.fieldsets)
I used version 1.10. Perhaps something has changed.
If someone finds an even simpler and elegant solution, show here.
Thanks to all )))