我有点问题。我想创建类似于网页目录的东西。在我的模型中,我创建了一个类Kategorie和类Firma。类Kategoria创建主要类别和子类别。在Firma课程中,我可以在女巫类别和子类别中定义新记录。我的问题是:如何在主页主要类别的html中显示,并在这张图片中稍微降低子类别
这是我的代码 的 models.py
from django.db import models
from django.contrib.auth.models import User
class Kategoria(models.Model):
name = models.CharField(max_length=250, verbose_name='Kategoria')
slug = models.SlugField(unique=True,verbose_name='Adres SEO')
parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE)
class Meta:
unique_together = ('slug', 'parent',)
verbose_name = 'Kategoria'
verbose_name_plural = 'Kategorie'
def __str__(self):
full_path = [self.name]
k = self.parent
while k is not None:
full_path.append(k.name)
k = k.parent
return ' / '.join(full_path[::-1])
class Firma(models.Model):
user = models.ForeignKey(User, default=1, verbose_name='Użytkownik', on_delete=models.CASCADE)
title = models.CharField(max_length=250, verbose_name='Nazwa firmy')
slug = models.SlugField(unique=True, verbose_name='Adres SEO')
category = models.ForeignKey('Kategoria', null=True, blank=True, verbose_name='Kategoria', on_delete=models.CASCADE)
content = models.TextField(verbose_name='Opis')
draft = models.BooleanField(default=False, verbose_name='Szablon')
publish = models.DateField(auto_now=False, auto_now_add=False)
class Meta:
verbose_name='Firma'
verbose_name_plural='Firmy'
def __str__(self):
return self.title
views.py
from django.shortcuts import render, get_object_or_404
from .models import Kategoria, Firma
def widok_kategorii(request):
kategorie = Kategoria.objects.filter().order_by('name')
context = {'kategorie': kategorie}
return render(request, 'ogloszenia/index.html', context=context)
的index.html
{% include 'ogloszenia/header.html' %}
Wyświetl kategorie<br>
{% for kategoria in kategorie %}
<b>{{kategoria.name}}<br></b>
{% endfor %}
{% include 'ogloszenia/footer.html' %}
答案 0 :(得分:2)
所以问题是子类别,对吧?
您可以在模板中使用inclusion_tag
,如我在此处提到的那样:
Tree Structure (Foreign Keys to itself) and templates
如果您需要渲染多个子类别,那么就像我在链接中提到的那样。
但如果你只需要第一级,那么它非常简单:
<强> views.py:强>
获取没有任何父级的类别(第2行)
def widok_kategorii(request):
### Get the categories without any parent.
kategorie = Kategoria.objects.filter(parent=None).order_by('name')
context = {'kategorie': kategorie}
return render(request, 'ogloszenia/index.html', context=context)
<强>模板:强>
{% include 'ogloszenia/header.html' %}
Wyświetl kategorie<br>
<ul>
{% for kategoria in kategorie %}
<li>
{{kategoria.name}}
{% if kategoria.children.count > 0 %}
<ul>
{% for sub in kategoria.children.all %}
<li>{{ sub.name }}</li>
{% endfor %}
</ul>
{% endif %}
</li>
{% endfor %}
</ul>
{% include 'ogloszenia/footer.html' %}
您可以将其设计为看起来像您发布的图片,但这是实现此类设计的树结构的方法。
答案 1 :(得分:-1)
在模板中,试试这个:
{% for kategoria in kategorie %}
<b>{{kategoria.name}}<br></b>
{% for subkategoria in kategoria_set.all %}
<b>{{subkategoria.name}}<br></b>
{% endfor %}
{% endfor %}