【发布时间】:2019-02-07 10:33:13
【问题描述】:
我有不同的 django 模型,它们是相同的,例如
- 项目类别
- 库存类别
- 菜单类别
- 费用类别
所有这些模型都具有相同的属性。
我想使用单个 html 页面,即 category_list.html 将这些模型显示为列表。我不想使用不同的页面,如 item_category_list.html、inventroy_category_list.html、menu_category_list.html 等。每个页面都包含 page header,这是 h1 标签中表示的页面的实际标题。我想针对当前加载的页面进行更改。
注意:我正在使用通用视图来列出项目,我目前正在使用上下文来识别哪个视图正在发送响应。
任何帮助将不胜感激。
views.py
class ItemCategoryList(ListView):
model = ItemCategory
template_name = 'app/category_list.html'
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
# Add in a QuerySet of all the books
context['page'] = 'Item'
return context
class InventoryCategoryList(ListView):
model = InventoryCategory
template_name = 'app/category_list.html'
class ExpenseCategoryList(ListView):
model = ExpenseCategory
template_name = 'app/category_list.html'
models.py
class ItemCategory(models.Model):
name = models.CharField(max_length=30)
description = models.CharField(max_length=300, null=True, blank=True)
image = models.ImageField(upload_to="uploads/item_categories/", null=True, blank=True)
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
class InventoryCategory(models.Model):
name = models.CharField(max_length=30)
description = models.CharField(max_length=300, null=True, blank=True)
image = models.ImageField(upload_to="uploads/inventory_categories/", null=True, blank=True)
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
class ExpenseCategory(models.Model):
name = models.CharField(max_length=30)
description = models.CharField(max_length=300, null=True, blank=True)
image = models.ImageField(upload_to="uploads/expense_categories/", null=True, blank=True)
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
【问题讨论】:
-
如果所有模型都具有相同的属性,那么首先将它们定义为单独的模型是否有意义?您可以限制
ForeignKey可以指向的查询集。因此,您可以为假设的Category模型定义type属性。 -
你会发布到目前为止的视图代码吗?
-
我添加了代码。
-
@Willem Van Onsem,你能举个例子吗?
标签: django django-templates django-urls