Django模板中的admin.StackedInline

kzmpq1sx  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(101)

我在使用Django。我在www.example.com上做了一个菜单类models.py

class Menu(models.Model):
nome = models.CharField(max_length=255)
data = models.DateTimeField(auto_now=False, auto_now_add=True)

class Meta:
    verbose_name_plural = 'Menu'

# Python 2
def __unicode__(self):
    return self.nome

# Python 3
def __str__(self):
    return self.nome

字符串
子菜单类:

class Submenu(models.Model):
nome = models.CharField(max_length=255)
data = models.DateTimeField(auto_now=False, auto_now_add=True)
menu = models.ForeignKey(Menu, on_delete=models.CASCADE)

class Meta:
    verbose_name_plural = 'Submenu'

# Python 2
def __unicode__(self):
    return self.nome

# Python 3
def __str__(self):
    return self.nome


然后在admin.py中我添加了:

class SubmenuAdmin(admin.StackedInline):
model = Submenu
extra = 0

class MenuAdmin(admin.ModelAdmin):
list_display = ['__str__']
inlines = [SubmenuAdmin,]

class Meta:
    model = Menu

admin.site.register(Menu, MenuAdmin)


现在,我的目标是能够打印模板中的各种菜单,并在每个相应的菜单下打印各种子菜单,如图所示:


的数据
在views.py上,我做了这样的事情:

def Home(request):
menus = Menu.objects.all().order_by('-data')
submenu_set = Submenu.objects.all().order_by('-data')
context = {
    'menus':menus,
    'submenu_set':submenu_set,
}
return render(request, 'index.html', context)

rlcwz9us

rlcwz9us1#

在模板中,您可以执行以下操作:

<ul>
    {% for menu in menus %}
        <li>
            {{ menu }} (menu)
            <ul>
                {% for submenu in menu.submenu_set.all %}
                    <li>
                        {{ submenu }} (submenu)
                    </li>
                {% endfor%}
            <ul>
        </li>
    {% endfor%}
</ul>

字符串
但我认为你可以做得更好:
只有一个类菜单:

class Menu(models.Model):
    nome = models.CharField(max_length=255)
    data = models.DateTimeField(auto_now=False, auto_now_add=True)
    parent = models.ForeignKey('self', related_name='children' on_delete=models.CASCADE, required=False)


在模板中:

<ul>
    {% for menu in menus %}
        <li>
            {{ menu }} (menu)
            <ul>
                {% for submenu in menu.children.all %}
                    <li>
                        {{ submenu }} (submenu)
                    </li>
                {% endfor%}
            <ul>
        </li>
    {% endfor%}
</ul>

相关问题