Django:创建一个管理部分,从多个模型收集信息

2024-09-30 22:22:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我被要求在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

^{pr2}$

但是当我进入/admin/core/configurationoverview/

^{3}$

但我已经定义了app_label: core!有什么提示吗?在

*编辑*

这是我运行的空迁移:

class Migration(migrations.Migration):
    dependencies = [...]
    operations = [
        migrations.CreateModel(
            name='ConfigurationOverview',
            fields=[],
            options={
                'managed': False,
                'verbose_name': 'Configuration overview'
            },
        ),
    ]

Tags: djangonamecoreselfgetadminondelete
1条回答
网友
1楼 · 发布于 2024-09-30 22:22:41

您可以尝试添加常规视图,并要求用户是工作人员。在

views.py

from django.contrib.admin.views.decorators import staff_member_required

@staff_member_required
def configuration_overview(request):
    aa = ModelA.objects.all() # customize this queryset if neccesary, paginate ...
    bb = ModelB.objects.all() # customize this queryset if neccesary, paginate ...
    cc = ModelC.objects.all() # customize this queryset if neccesary, paginate ...

    return render(request, 'admin/core/configurationoverview/change_list.html', context={'aa': aa, 'bb': bb, 'cc': cc})

urls.py

^{pr2}$

相关问题 更多 >