【发布时间】:2020-12-18 21:37:40
【问题描述】:
我是 Python/Django 的初学者,我目前正在尝试制作一个用于制作收集日志的基本应用程序。首先,用户选择一个类别,然后在该类别下插入对象。
我在 models.py 中有两个类,代码如下:
class object_category(models.Model):
"""This class contains the users different categories"""
CATEGORY_CHOICES = [
('category1', 'category1'),
('category2', 'category2'),
('category3', 'category3'),
]
"""Plural for multiple categories"""
class Meta:
verbose_name_plural = 'Categories'
"""Returns the above stated choices"""
category = models.CharField(max_length=50, choices=CATEGORY_CHOICES)
def __str__(self):
return self.category
class object_name(models.Model):
"""This class contains the object name that is housed within a certain category"""
"""Links the object to one of the chosen categories"""
category = models.ForeignKey(object_category, on_delete=models.CASCADE)
# Placeholder for connection with a plant database API
object = models.CharField(max_length=50)
"""Return the object input from the user"""
def __str__(self):
return self.object
这里是views.py代码:
def collection(request):
"""The page that opens the collection of objects"""
object_category = Object_category.objects.order_by('category')
object_name = Object_name.objects.order_by('object')
context = {
'object_category': object_category,
'object_name': object_name
}
return render(request, 'plntz_main/collection.html', context)
最后这是我的 html 文档代码:
{% for category in object_category %}
{% for object in object_name %}
<h3>{{ category }}</h3>
<li>{{ object }}</li>
{% empty %}
<li>No category has been added yet.</li>
{% endfor %}
{% endfor %}
这会显示类别和对象,但它们没有链接。
我要显示的是:
- 用户选择的类别
- 该特定类别中的每个对象
谁能解释我是如何修改代码得到这个结果的?
对不起,这是一团糟。我是新手,这是我第一次尝试一个项目,也是我在 stackoverflow 上的第一个问题。
谢谢!
【问题讨论】: