Search code examples
djangodjango-adminmodels

Django: Admin, adding some new filters to a multiple choice field


I am building an article site using django. I've added many to many relation between my articles this way:

class Article (models.Model):
    # Tiny url
    url = models.CharField(max_length = 30, unique=True)
    is_published = models.BooleanField()
    author = models.CharField(max_length = 150)
    title = models.CharField(max_length = 200)
    short_description = models.TextField(max_length = 600)
    body = tinymce_models.HTMLField()
    related = models.ManyToManyField("self")

Now in my admin site, I see multiple select box ( see image here http://img.skitch.com/20091017-mfs2mbhbuudk2rgquium1bu61d.png)

What I want is to use this box usable for a user who will chose articles to bind them to a current one. So for example, is there a way to add some filtering there? E.g. If I would like to filter all articles by section? And then dismiss previous results and filter the whole set by name, etc?

Thanks in advance

+++

I am trying to investigate possibility to add filter horizontal to admin. But after I added it this way:

class ArticleAdmin(admin.ModelAdmin):
    exclude = ('video', )

    js = ('/site_media/js/tiny_mce/tiny_mce.js', 
          )
    list_display = ('title', 'author', 'section', 'is_published', 'pub_date')
    list_filter = ('author', 'section', 'is_published', 'pub_date')
    filter_horizontal = ['related', ]
    search_fields = ['body', 'title', 'short_description', 'seo_keywords']

All articles vanished from admin :(


Solution

  • If you look for basic filtering, try this or that:

    If you want to customize filtering, you could actually do it. A little guide:

    Subclass forms.SelectMultiple or directly the existing FilteredSelectMultiple from django.contrib.admin.widgets and make it do what you want.

    Then subclass ModelAdmin in your admin.py and overwrite formfield_for_manytomany (look in django.contrib.admin.options for that method) and exchange the existing widget with your new one.