In the change list of the django admin, I want to use list_editable to display a django-autocomplete widget for a ManyToManyField.
I found something similar here: list_editable and widgets
Normally including a ManyToManyField in list_display raises an ImproperlyConfigured exception, eg:
""'BookAdmin.list_display[2]', 'author' is a ManyToManyField which is not supported."
I (perhaps unwisely) removed 3 lines from contrib/admin/validate.py to bypass the exception. :)
I now have it spitting out the following, which is close(?) but no cigar.
<django.db.models.fields.related.ManyRelatedManager object at 0x1032a85d0>
Any thoughts on how to proceed? Is there a better way of doing this?
Here's what I have at the moment: (AuthorAutocomplete is working fine in the regular admin form)
class AuthorAutocomplete(AutocompleteSettings):
search_fields = ('first_name', 'last_name')
class BookAdmin(AutocompleteAdmin, admin.ModelAdmin):
def get_changelist_form(self, request, **kwargs):
kwargs.setdefault('form', AuthorAutocompleteForm)
return super(BookAdmin, self).get_changelist_form(request, **kwargs)
list_display = ['isbn', 'title', 'author', 'publisher']
#...
class AuthorAutocompleteForm(forms.ModelForm):
class Meta:
model = Book
author = AuthorAutocomplete
Thanks!
This is an old topic, but I'm hoping this might help someone else.
To get the values for a ManyToMany field so you can display their values you can do the follow. I'm using list_display as an example.
class TestAdmin(admin.ModelAdmin):
def get_some_value(self):
return ", " . join([x.__str__() for x in self.manytomany_field.all()])
list_display(get_some_value)
get_some_value.short_description = 'Title' #sets column header to Title
Silly me. I thought that William's manytomany_field was a built-in ModelAdmin object. So I ran his code as is (after putting in the missing parenthesis after join).
Strange to say, it ran without producing an error message. But (None) appeared when I was supposed to get values. And I thought it was strange that I couldn't find anything when I Googled "django model.Admin.manytomany_field". Hah!
So eventually I realized that I was to put the NAME of the many-to-many field in place of manytomany_field. It works!
来源:https://stackoverflow.com/questions/7629786/manytomanyfield-widget-in-a-django-admin-change-list