How to change the display of Django admin when use ManyToManyField

折月煮酒 提交于 2020-01-06 08:33:14

问题


I'm coding a news website.News model has a ManyToManyField foreign key named tag.

Here is my News model:

class News(models.Model):
   title = models.CharField(max_length=100, verbose_name='title') 
   category = models.ForeignKey(Category, on_delete=models.CASCADE, 
   related_name="cate", blank=True, verbose_name='Category')
   tag = models.ManyToManyField(Tag, blank=True, verbose_name='Tags')

    class Meta:
        verbose_name = "新闻"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title

Here is my tag model:

class Tag(models.Model):
    name = models.CharField(max_length=40)

    class Meta:
        verbose_name = "Tag"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name

Now I find a issue is, in the admin, the display of tag menu window is too small as this screen shot:

However in practical projects for example a high traffic news website, there will be dozens of tags or maybe nearly 100 tags, it is really hard and frustrated to select a tag among so many tags in such a small menu window.

Here is my admin.py:

class TagAdmin(object):
    list_display = ['name']
    search_fields = ['name']
    list_filter = ['name']

xadmin.site.register(Tag, TagAdmin)

So is any good idea can make it easier?By the way I'm using Xadmin. I think maybe I should change the css of that place.

Any friend can help?Thank you so much!


回答1:


Override the django admin css, and point it to that file

from your_app.models import News

@admin.register(News)
class NewsAdmin(admin.ModelAdmin):
    filter_horizontal = ('tag',)

    class Media:
        css = {
            'all': ('your_file.css',), # file located in your static direcotry
        }

Here are some class that you can override:

.selector-available,
.selector-chosen {
    width: 100px;
}

.selector .selector-available input {
    width: 200px;
}

.selector select {
    width: 300px;
}

.selector {
    width: 400px;
}



回答2:


Really appreciate all the answers.

And I have found the best and easiest way to solve it!

First:if you are using admin, you just need to add in admin.py:

filter_horizontal = ('tags', )

. If you are using Xadmin,just code:

style_fields = {'tag': 'm2m_transfer'}

specific example:

class NewsAdmin(object):
    list_display     = ['title',]
    search_fields    = ['title', ]
    list_filter      = ['title', ]
    style_fields     = {'tag': 'm2m_transfer'}


来源:https://stackoverflow.com/questions/50164836/how-to-change-the-display-of-django-admin-when-use-manytomanyfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!