75145

Django ModelAdmin.get_urls() not registering custom urls

<h3>Question</h3>

I am trying to create custom views for my models in Django admin site. I created ModelAdmin for my model named Document like this:

from django.http import HttpResponse from django.urls import path from django.contrib import admin from my_app.models import Document @admin.register(Document) class DocumentAdmin(admin.ModelAdmin): def get_urls(self): urls = super().get_urls() custom_urls = [ path('my-view/', self.admin_site.admin_view(self.my_view)) ] return urls + custom_urls def my_view(self, request): return HttpResponse('test')

According to the docs (v2.1) I should be able to access my_view with /admin/my_app/document/my-view but when I try to visit this URL django redirects me to admin homepage with the following warning:

Document with ID "my-view" doesn't exist. Perhaps it was deleted?

So it looks like django cannot see my custom url. What am I missing? How can I get this to work?


<h3>Answer1:</h3>

This is just a matter of URL ordering; the generic admin change view is processed first and is capturing your request for "my-view" as a slug. You can change this by putting your URLs first, which is what is actually done in the example you link to:

return custom_urls + urls

来源:https://stackoverflow.com/questions/52144009/django-modeladmin-get-urls-not-registering-custom-urls

Recommend