Jaco Pretorius
Jaco Pretorius

Reputation: 24840

Django custom list view in admin

One of the objects I am managing in my django site will only ever have one instance in the database. I therefore want to change the list view to simply redirect to the 'edit' page for this first object.

So basically when you hit /admin/my_site/widgets I want to redirect to /admin/my_site/widget/1. I have tried a custom view, a custom template, etc, but I can't find an easy way of doing this (or any way of doing this for that matter).

It's almost like I want to do something like this (doesn't work because I can't figure out how to change the list view):

class WidgetAdmin(admin.ModelAdmin):
    def list_view(self, request):
        widget = Widget.objects.all()[0]
        return HttpResponseRedirect('/admin/my_site/widget/%s' % widget.id)

I've also tried change the url's to match the list request and do a redirect there, but I can't seem to match the list request with anything other than a complete blanket regex, i.e. (r/^.*$/) which means I just get an infinite loop redirect.

Upvotes: 1

Views: 3097

Answers (2)

Daniel Backman
Daniel Backman

Reputation: 5241

I needed the same thing. I solved it slighty different using the changelist_view from ModelAdmin. Using your example it would look somthing like:

class MySingleEditAdmin(admin.ModelAdmin):
   def changelist_view(self, request, extra_context=None):
       object, created = self.get_my_object()
       url = reverse('admin:%s_%s_change' %(object._meta.app_label, object._meta.module_name),  args=[object.id] )
       return HttpResponseRedirect(url)


class WidgetAdminAdmin(MySingleEditAdmin):
   def get_my_object(self):
       return Widget.objects.get_or_create(pk=1, ...default_data...)

Upvotes: 1

Jaco Pretorius
Jaco Pretorius

Reputation: 24840

Ok this is how I sorted it out.

class WidgetAdmin(admin.ModelAdmin):
    def list_view(self, request):
        widget = Widget.objects.all()[0]
        return HttpResponseRedirect('/admin/my_site/widget/%s' % widget.id)

    def get_urls(self):
        from django.conf.urls.defaults import *
        urls = super(WidgetAdmin, self).get_urls()
        my_urls = patterns('',
                    (r'^$', admin.site.admin_view(self.list_view))
                )
        return my_urls + urls

Upvotes: 0

Related Questions