gpt4 book ai didi

python - 在 django admin 创建新的自定义 View

转载 作者:行者123 更新时间:2023-11-28 18:14:38 25 4
gpt4 key购买 nike

抱歉,我在 django 还是个新手。我想在管理站点创建与我的模型无关的自定义 View 。我已阅读文档 ( https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_urls ),但不起作用。阅读一些教程也不起作用......这是我尝试过的:

管理员.py

from django.contrib import admin
from django.urls import path
from .models import Question
from django.http import HttpResponse

class CustomAdminView(admin.ModelAdmin):
def get_urls(self):
urls = super().get_urls()
my_urls = [
path(r'^my_view/$', self.admin_site.admin_view(self.my_view))
]
urls = my_urls + urls
return urls


def my_view(self, request):
return HttpResponse("Hello, world.")


admin.site.register(Question)

网址.py

from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url

admin.autodiscover()
urlpatterns = [
path(r'polls/',include('polls.urls')),
path('admin/', admin.site.urls),
]

当我转到 admin/my_view 时,结果是 404 not found。

我也尝试过扩展 AdminView。

管理员.py

from django.contrib.admin import AdminSite
from django.urls import path
from .models import Question
from django.http import HttpResponse

class CustomAdminView(AdminSite):
def get_urls(self):
urls = super().get_urls()
my_urls = [
path(r'my_view/', self.admin_view(self.my_view))
]
urls = my_urls + urls
return urls


def my_view(self, request):
return HttpResponse("Hello, world.")


custom_admin = CustomAdminView()
custom_admin.register(Question)

网址.py

from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
from polls.admin import custom_admin

admin.autodiscover()
urlpatterns = [
path(r'polls/',include('polls.urls')),
path('admin/', custom_admin.urls),
]

我在 admin/my_view 上没有收到 404 错误。但是,不显示默认模型(用户和其他)。那里只有我的“问题”模型。上一个仍然具有默认模型。

如何以正确的方式制作自定义管理 View ?谢谢。

最佳答案

解决了。我正在使用我的第二个 admin.py 和 urls.py 片段并根据以下答案注册 django 的默认模型:Django (1.10) override AdminSite

管理员.py

from django.contrib.admin import AdminSite
from django.http import HttpResponse
from django.urls import path
from .models import Question
from django.contrib.auth.models import Group, User #add these moduls
from django.contrib.auth.admin import GroupAdmin, UserAdmin #and these

class CustomAdminView(AdminSite):
def get_urls(self):
urls = super().get_urls()
my_urls = [
path(r'my_view/', self.admin_view(self.my_view))
]
urls = my_urls + urls
return urls


def my_view(self, request):
return HttpResponse("Hello, world.")


custom_admin = CustomAdminView()
custom_admin.register(Question)

#register the default model

custom_admin.register(Group, GroupAdmin)
custom_admin.register(User, UserAdmin)

关于python - 在 django admin 创建新的自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49176113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com