Reputation: 53990
I am writing a little app to allow an AddThis share field in the django admin change list to allow the user share the object they are currently editing (as well as seeing the share count):
Taking a simple BlogEntry as an example, I have created a custom ModelAdmin:
class AddThisAdmin(admin.ModelAdmin):
addthis_config = {
'title_field' : None,
'description_field' : None,
'url_field' : None,
'image_field' : None,
}
def get_form(self, request, obj=None, *args, **kwargs):
metaform = super(AddThisAdmin, self).get_form(request, obj, **kwargs)
if obj:
# Grab users config and find the fields they specified ...
metaform.base_fields['add_this'] = AddThisField(self.add_this)
return metaform
Which is inherited in the users BlogEntryAdmin like so:
class BlogEntryAdmin(admin.ModelAdmin, AddThisAdmin):
addthis_config = {
'title_field' : 'blog_title',
'description_field' : 'blurb',
}
where the addthis_config
allows the user to specify the fields in their BlogEntry object from where to pull the title/description/url and image used in AddThis. This all works really nicely until I decide to use a custom fieldset in the BlogEntryAdmin:
class BlogEntryAdmin(admin.ModelAdmin, AddThisAdmin):
addthis_config = {
'title_field' : 'blog_title',
'description_field' : 'blurb',
}
fieldsets = [{ ... }]
'BlogEntry.fieldsets0['fields']' refers to field 'add_this' that is missing from the form.
I understand that this is happening because the django admin runs a validation on the fieldsets (django.contrib.admin.validation) on the BlogEntryAdmin class before it is actually instantiated (and my custom field is inserted).
tldr : Is there a way I can tell the django.contrib.admin.validation
to ignore the field in the fieldset?
Upvotes: 0
Views: 1564
Reputation: 308949
It's not documented, but you could use the get_fieldsets
method to define your fieldsets. As an example, look at how Django changes the fieldsets in the UserAdmin
when adding new users.
I've not tested this, but I believe it will avoid the fieldset
validation.
Upvotes: 1
Reputation: 239350
The typical approach is to provide base form like AddThisAdminForm
which has the required field(s), and the make other ModelAdmin's forms inherit from that. It looks like you're trying to avoid that and auto insert the fields into whatever form is being used. If you insist on that approach, something like the following should work much better:
def get_form(self, request, obj=None, **kwargs):
ModelForm = super(AddThisAdmin, self).get_form(request, obj, **kwargs)
class AddThisForm(ModelForm):
add_this = AddThisField(self.add_this)
return AddThisForm
Upvotes: 2