I need to add a custom view to the Django Admin. This should be similar to a standard ChangeList view for a certain model, but with a custom result set. (I need to display all models having some date or some other date less than today, but this is not really relevant).
One way I can do this is by using the Admin queryset
method, like
class CustomAdmin(admin.ModelAdmin):
...
def queryset(self, request):
qs = super(CustomAdmin, self).queryset(request)
if request.path == 'some-url':
today = date.today()
# Return a custom queryset
else:
return qs
This makes sure that ...
The problem is that I do not know how to tie some-url
to a standard ChangeList view.
You can fully customize the admin by changing the templates used to render pages. The Django template engine has a defined order for loading templates. When it loads a template, it uses the first template that matches the name. You can override admin templates by using the same directory structure and file names.
To login to the site, open the /admin URL (e.g. http://127.0.0.1:8000/admin ) and enter your new superuser userid and password credentials (you'll be redirected to the login page, and then back to the /admin URL after you've entered your details).
The default templates used by the Django admin are located under the /django/contrib/admin/templates/ directory of your Django installation inside your operating system's or virtual env Python environment (e.g. <virtual_env_directory>/lib/python3. 5/site-packages/django/contrib/admin/templates/ ).
So you want a second URL that goes to the changelist view so you can check which of the two it was by the requested URL and then change the queryset accordingly? Just mimick what django.contrib.admin.options does and add another URL to the ModelAdmin.
Should look something like this:
class CustomAdmin(admin.ModelAdmin):
def get_urls(self):
def wrap(view):
def wrapper(*args, **kwargs):
kwargs['admin'] = self # Optional: You may want to do this to make the model admin instance available to the view
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
# Optional: only used to construct name - see below
info = self.model._meta.app_label, self.model._meta.module_name
urlpatterns = patterns('',
url(r'^my_changelist/$', # to your liking
wrap(self.changelist_view),
name='%s_%s_my_changelist' % info)
)
urlpatterns += super(CustomAdmin, self).get_urls()
return urlpatterns
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With