Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin, page not found in custom view

Tags:

python

django

I encountered very annoying problem.

I have created my own AdminSite like this:

from django.contrib import admin
from django.template.response import TemplateResponse
from django.urls import path

class MyAdminSite(admin.AdminSite):

    def get_urls(self):
        urls = super().get_urls()
        my_urls = [
            path('statistics/', self.admin_view(self.statistics), name='statistics'),
        ]
        return urls + my_urls

    def statistics(self, request):
        context = dict(
            self.each_context(request),
        )
        return TemplateResponse(request, 'admin/statistics.html', context)

I have created my own AdminConfig and assigned it into my INSTALLED_APPS, created html file, then in my root urls added it like this:

 urlpatterns = [
    url(r'^admin/', admin.site.urls),
 ]

I have logged in into my admin page and when I'm trying to open localhost:8000/admin/statistics I receive this:

Page not found (404)
Request URL:    http://localhost:8000/admin/statistics/

Why this is happening? Did I miss something?

Update

I have added print on my get_urls and it showed this.(I removed unnecessary urls):

[
<URLPattern '' [name='index']>, 
<URLPattern 'login/' [name='login']>, 
<URLPattern 'logout/' [name='logout']>, 
<URLPattern 'password_change/' [name='password_change']>, 
<URLPattern 'password_change/done/' [name='password_change_done']>, 
<URLPattern 'autocomplete/' [name='autocomplete']>, 
<URLPattern 'jsi18n/' [name='jsi18n']>, 
<URLPattern 'r/<int:content_type_id>/<path:object_id>/' [name='view_on_site']>, 
<URLResolver <URLPattern list> (None:None) 'auth/group/'>,  
<URLPattern '(?P<url>.*)$'>, 
<URLPattern 'statistics/' [name='statistics']>
]

Using python manage.py show_urls | grep statistics shows me this:

/admin/statistics/   project.admin.statistics    admin:statistics
like image 213
Mr.D Avatar asked Jul 22 '21 08:07

Mr.D


2 Answers

Well. I'm going to answer to my own question, in order to help other people.

The solution of this problem was to switch returning url addition like this:

 return my_urls + urls

my_urls comes first and the other urls.

Why this is happening? Because urls' last path contains some kind of big wildcard url that just overwrites my own. That is why I needed to add first my new urls.

Thanks for @lucascavalcante

like image 143
Mr.D Avatar answered Sep 28 '22 17:09

Mr.D


Try invert the order of return in your get_url function:

return my_urls + urls
like image 30
lucascavalcante Avatar answered Sep 28 '22 19:09

lucascavalcante