1
votes

django has a way to show a ForeignKey in its parent inline.[refer]
What I need is completely inversed.

I have a navbar in my site, I only need one Menu model to control the name and url of MenuButtons under the navbar. And the number of child MenuButton is fixed to 4(would not change in future).
So,the most easy and proper way to designed my menu models is below:

class MenuButton(models.Model):
    class Meta:
        verbose_name = u"菜单按钮"
        verbose_name_plural = u"菜单按钮"

    name = models.CharField(u'名字', max_length=8)
    url = models.CharField(u'链接', max_length=100)
    priority = models.IntegerField(u'排序优先级', null=True, blank=True)
    create_time = models.DateTimeField(u'创建时间', auto_now_add=True)
    update_time = models.DateTimeField(u'更新时间', auto_now=True)

    def __unicode__(self):
        return self.name


class Menu(models.Model):
    class Meta:
        verbose_name = u"菜单"
        verbose_name_plural = u"菜单"

    button_1 = models.ForeignKey(MenuButton, verbose_name=u'按钮1', related_name="button_1")
    button_2 = models.ForeignKey(MenuButton, verbose_name=u'按钮2', related_name="button_2")
    button_3 = models.ForeignKey(MenuButton, verbose_name=u'按钮3', related_name="button_3")
    button_4 = models.ForeignKey(MenuButton, verbose_name=u'按钮4', related_name="button_4")

I only want admin show one Menu.People can only change the four buttons in MenuAdmin edit form, neither delete nor add a new button.But I can't find the way with out build a custom field.

1
You can use has_add_permission, has_change_permission and has_delete_permission for your MenuButtonAdmin in order to manage permissions link - cansadadeserfeliz
I know that. for now, what I want to know is how to display the 4 button inline edit in MenuButton. - Mithril

1 Answers

2
votes

It's wrong by design. 2 solutions to fix that:

  1. Use normal foreign key inside MenuButton and limit count of buttons in other ways (better solution)
  2. User OneToOneFields instead of foreign keys (not that good as first, explained later)

When 1st solution used, you can limit and assure that there will be always 4 and only 4 buttons inside your admin (or view, if you will allow to edit it outside admin). There are max_num and min_num attributes that you can provide into inline admin. You can also override has_add_permission and has_delete_permission to remove at all add and remove features from admin, by returning false in all cases.

when using 2nd solution, you can also do that, but queries for getting all buttons will be more complex and less optimal. So you should stick to 1st design.