【发布时间】:2019-09-13 19:53:35
【问题描述】:
我被要求在 Django 项目的管理站点中添加一个新部分,该部分将从多个模型中收集信息(因为它是一个数据库视图),但我不允许在其中更改或添加表/视图数据库。
在 SO 中检查类似问题 custom page for Django admin,我最终尝试创建一个不会由 Django 管理的“假”模型,并在 get_urls 方法中添加自定义 URL。
让代码自己解释一下:
core/admin.py
class ConfigurationOverview(Model):
aa = ForeignKey(ModelA, on_delete=DO_NOTHING)
bb = ForeignKey(ModelB, on_delete=DO_NOTHING)
cc = ForeignKey(ModelC, on_delete=DO_NOTHING)
class Meta:
# Django won't consider this model
managed = False
# link to the index page at /admin
verbose_name = 'Configuration overview'
app_label = 'core'
@staticmethod
def all():
# gather info from ModelA, ModelB, ModelC and create a collection of ConfigurationOverviews
return []
@register(ConfigurationOverview)
class ConfigurationOverviewAdmin(ModelAdmin):
def get_urls(self):
urls = super(ConfigurationOverviewAdmin, self).get_urls()
my_urls = [
url(
r'^$', # /admin/core/configurationoverview/
self.admin_site.admin_view(self.list_view),
name='core_configurationoverview_list'
)
]
return my_urls + urls
def list_view(self, request):
context = {
'configuration_overviews': ConfigurationOverview.all(),
}
return render(request,
"admin/core/configurationoverview/change_list.html",
context)
templates/admin/core/configurationoverview/change_list.html
{% extends "admin/change_list.html" %}
{% block content %}
AAAA
{% endblock %}
但是当访问 /admin/core/configurationoverview/ 我得到了
NoReverseMatch at /admin/core/configurationoverview/
Reverse for 'app_list' with keyword arguments '{'app_label': ''}' not found. 1
但我已经定义了app_label: core!有什么提示吗?
* 编辑 *
这是我运行的空迁移:
class Migration(migrations.Migration):
dependencies = [...]
operations = [
migrations.CreateModel(
name='ConfigurationOverview',
fields=[],
options={
'managed': False,
'verbose_name': 'Configuration overview'
},
),
]
【问题讨论】:
-
数据库中是否有表/视图来表示实体ConfigurationOverview?因为即使模型不是由 django 管理的,表/视图也必须存在。
-
不,没有...(附加空迁移)...您将如何面对这个问题? (谢谢)
标签: python django django-templates django-admin