在Django 2.2中,是否有方法可以从管理员URL中删除应用程序名称?

huangapple go评论73阅读模式
英文:

Django 2.2 : Is there any way to remove app name from admin urls?

问题

I am using Django Built-in Admin panel, is there any way to remove app name from urls?

如果我想访问用户列表,它会重定向到 27.0.0.1:8000/admin/auth/user/,我是否可以使其成为 27.0.0.1:8000/admin/user/,而不带有应用程序名称 auth

谢谢,

英文:

I am using Django Built-in Admin panel, is there any way to remove app name from urls?

If I want to access User listing, it redirects me to 27.0.0.1:8000/admin/auth/user/ can I make it 27.0.0.1:8000/admin/user/ without the app name auth?

Thanks,

答案1

得分: 2

根据这里的文档,您可以创建一个自定义的AdminSite并重写get_urls方法。这段简单的代码应该可以胜任:

在您的common.admin.py文件中:

from django.contrib.admin import AdminSite

class MyAdminSite(AdminSite):

    def get_urls(self):
        urlpatterns = super().get_urls()
        for model, model_admin in self._registry.items():
            urlpatterns += [
                path('%s/' % (model._meta.model_name), include(model_admin.urls)),
            ]
        return urlpatterns


my_admin = MyAdminSite('My Admin')

my_admin.register(YourModel)
...

请注意,您需要使用新的自定义AdminSite实例来注册您的模型。

然后在您的项目的urls.py文件中:

from common.admin import my_admin as admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.urls),
    # 您的其他模式
]
英文:

As documented here you can create a custom AdminSite and override the get_urls method. This simple code should to the job:

In your common.admin.py

from django.contrib.admin import AdminSite

class MyAdminSite(AdminSite):

    def get_urls(self):
        urlpatterns = super().get_urls()
        for model, model_admin in self._registry.items():
            urlpatterns += [
                path('%s/' % (model._meta.model_name), include(model_admin.urls)),
            ]
        return urlpatterns


my_admin = MyAdminSite('My Admin')

my_admin.register(YourModel)
...

Note that you register your models with the new custom AdminSite instance.

Then in your projects urls.py

from common.admin import my_admin as admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.urls),
    # Your other patterns
]

huangapple
  • 本文由 发表于 2020年1月6日 22:14:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613628.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定