【发布时间】:2020-02-04 12:00:21
【问题描述】:
我有一个 Django 项目,我有一个 base.html,所有模板都从该项目继承。然后我在 base.html 中包含一个 category.html 文件,它只是我的导航栏。所以我有一个名为 Category 的模型,我想将此模型传递给 category.html 以显示我的类别。我不知道该怎么做?
base.html:
<!DOCTYPE html>
{% load static %}
<html lang="en" style="height: 100%;">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>{% block title %}{% endblock %}</title>
<!-- Google Fonts -->
{% comment %} <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <!-- Bootstrap core CSS --> {% endcomment %}
<link href="{% static 'fontawesome/css/all.css' %}" rel="stylesheet"> <!--load all styles -->
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
<!-- Material Design Bootstrap -->
<link href="{% static 'css/mdb.min.css' %}" rel="stylesheet">
<!-- Your custom styles (optional) -->
<link href="{% static 'css/style.min.css' %}" rel="stylesheet">
<!-- Mega menu style -->
<link href="{% static 'css/bs4megamenu.css' %}" rel="stylesheet">
{% block extra_head %}
{% endblock %}
{% block slideshow %}
{% endblock slideshow %}
</head>
<body>
<!-- Category Navbar -->
{% include 'category_navbar.html' %}
<!-- Category Navbar -->
<!-- Body Content -->
{% block content %}{% endblock %}
<!-- Body Content -->
<!-- Footer and scripts-->
{% include 'footer.html' %}
{% include 'scripts.html' %}
<!-- Footer and scripts-->
</body>
</html>
模型.py:
class Category(models.Model):
category_name = models.CharField(max_length=20, default="general")
category_description = models.TextField()
category_picture = models.ImageField(upload_to="categories/images/", blank=True)
slug = models.SlugField()
parent = models.ForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.CASCADE)
class Meta:
unique_together = ('slug', 'parent',) #enforcing that there can not be two
verbose_name_plural = "categories"
def __str__(self):
full_path = [self.category_name]
k = self.parent
while k is not None:
full_path.append(k.category_name)
k = k.parent
return ' -> '.join(full_path[::-1])
def save(self, *args, **kwargs):
self.slug = slugify(self.category_name)
super(Category, self).save(*args, **kwargs)
【问题讨论】:
-
使用自定义模板标签或上下文处理器。
标签: python django python-3.x