如何显示类别名称和描述?

时间:2019-09-27 02:05:41

标签: python django django-models django-templates django-views

如何将类别模型中的类别名称和简短描述显示在Categories.html页面上?我问这个问题是因为我无法弄清楚,我从互联网上获取了代码,因此不清楚它是如何工作的。因此,现在的代码将您带到example.com/cat-slug之类的页面,然后显示该类别下的所有帖子,但是如何在该页面上显示当前类别的名称(categories.html)以及类别说明太?

models.py:

class Category(models.Model):
    name = models.CharField(max_length=100)
    short_desc = models.CharField(max_length=160)
    slug = models.SlugField()
    parent = models.ForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.CASCADE)

    class Meta:
        unique_together = ('slug', 'parent',)
        verbose_name_plural = "categories"

    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 Post(models.Model):
    user =  models.CharField(max_length=50, default=1)
    title = models.CharField(max_length=120)
    short_desc = models.CharField(max_length=50)
    category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE)
    tags = TaggableManager()
    content = models.CharField(max_length=1000)
    publish = models.DateField(auto_now=False, auto_now_add=False,)
    slug = models.SlugField(unique=True)

    def __str__(self):
        return self.title

    def get_cat_list(self):
        k = self.category
        breadcrumb = ["dummy"]
        while k is not None:
            breadcrumb.append(k.slug)
            k = k.parent

        for i in range(len(breadcrumb)-1):
            breadcrumb[i] = '/'.join(breadcrumb[-1:i-1:-1])
        return breadcrumb[-1:0:-1]

views.py:

def show_category(request, hierarchy=None):
    category_slug = hierarchy.split('/')
    category_queryset = list(Category.objects.all())
    all_slugs = [ x.slug for x in category_queryset ]
    parent = None
    for slug in category_slug:
        if slug in all_slugs:
            parent = get_object_or_404(Category, slug=slug, parent=parent)
        else:
            post = get_object_or_404(Post, slug=slug)
            post_related = post.tags.similar_objects()
            comments = post.comments.filter(active=True)
            instance = get_object_or_404(Post, slug=slug)
            breadcrumbs_link = instance.get_cat_list()
            category_name = [' '.join(i.split('/')[-1].split('-')) for i in breadcrumbs_link]
            breadcrumbs = zip(breadcrumbs_link, category_name)

            if request.method == 'POST':
                comment_form = CommentForm(data=request.POST)
                if comment_form.is_valid():
                    new_comment = comment_form.save(commit=False)
                    new_comment.post = post
                    new_comment.save()
            else:
                comment_form = CommentForm()

            context = {
                'post': post,
                'post_related': post_related,
                'comments': comments,
                'comment_form': comment_form,
                'instance': instance,
                'breadcrumbs': breadcrumbs,
            }
            return render(request, "blog/post_detail.html", context)
    context = {
        'post_set': parent.post_set.all(),
        'sub_categories': parent.children.all(),
    }
    return render(request, "blog/categories.html", context)

categories.html:

{% extends 'base.html' %}

{% block content %}

Viewing: {{ name }} Category
{{ short_desc }}

<div class="container">
    <div class="row">
    {% if post_set %}
    {% for post in post_set %}
        <div class="col-lg-8 col-md-10 mx-auto">
            <div class="post-preview">
                <a href="/blog/{{ post.slug }}">
                    <h2 class="post-title">
                        {{ post.title }}
                    </h2>
                    <h3 class="post-subtitle">
                        {{ post.short_desc }}
                    </h3>
                </a>

                <p class="post-meta">Posted by
                    <a href="#">{{ post.user }}</a> at {{ post.publish }} in {{ post.category }}
                    <br />
                    {% for tag in post.tags.all %}
                        <font class="trigger blue lighten-4" size="3rem">{{ tag.name }}</font>
                    {% endfor %}
                </p>
            </div>
            <hr>
        </div>
    {% endfor %}
    {% else %}
        <p>No post found in this category.</p>
    {% endif %}
    </div>
</div>

{% endblock %}

1 个答案:

答案 0 :(得分:0)

我认为parent的实现是不正确的,因为在循环的每次迭代中,父级都会被更新。

for slug in category_slug:
    if slug in all_slugs:
        parent = get_object_or_404(Category, slug=slug, parent=parent)  # <-- with each iteration, value of parent will be updated.

相反,您可以这样定义父项:

parent = Category.objects.filter(slug__in=category_slug, parent=None).first()

context = {
        'category': parent,  # send the category explicitly through the context
        'post_set': parent.post_set.all(),
        'sub_categories': parent.children.all(),
    }

并更新模板:

Viewing: {{ category.name }} Category
{{ category.short_desc }}