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

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

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文件中:

  1. from django.contrib.admin import AdminSite
  2. class MyAdminSite(AdminSite):
  3. def get_urls(self):
  4. urlpatterns = super().get_urls()
  5. for model, model_admin in self._registry.items():
  6. urlpatterns += [
  7. path('%s/' % (model._meta.model_name), include(model_admin.urls)),
  8. ]
  9. return urlpatterns
  10. my_admin = MyAdminSite('My Admin')
  11. my_admin.register(YourModel)
  12. ...

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

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

  1. from common.admin import my_admin as admin
  2. from django.urls import path
  3. urlpatterns = [
  4. path('admin/', admin.urls),
  5. # 您的其他模式
  6. ]
英文:

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

  1. from django.contrib.admin import AdminSite
  2. class MyAdminSite(AdminSite):
  3. def get_urls(self):
  4. urlpatterns = super().get_urls()
  5. for model, model_admin in self._registry.items():
  6. urlpatterns += [
  7. path('%s/' % (model._meta.model_name), include(model_admin.urls)),
  8. ]
  9. return urlpatterns
  10. my_admin = MyAdminSite('My Admin')
  11. my_admin.register(YourModel)
  12. ...

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

Then in your projects urls.py

  1. from common.admin import my_admin as admin
  2. from django.urls import path
  3. urlpatterns = [
  4. path('admin/', admin.urls),
  5. # Your other patterns
  6. ]

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:

确定