Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin: redirect to object change page if only one exists in list

I'm using Django for an application, and wondering about an option in the admin. Is it possible for django admin to redirect to the details page of an object, if only one exists in the list view?

For example, if only this object exists: enter image description here

redirect immediately to the change view on this object, without needing the user to click on the object.

I'm not using any custom view. I couldn't find any solution after 2 hours of search.

Thanks!

like image 330
Crispy Holiday Avatar asked Feb 01 '26 12:02

Crispy Holiday


1 Answers

You can try this

def changelist_view(self, request, extra_context=None):
    if self.model.objects.all().count() == 1:
        obj = self.model.objects.all()[0]
        return HttpResponseRedirect(reverse("admin:%s_%s_change" %(self.model._meta.app_label, self.model._meta.model_name), args=(obj.id,)))
    return super(ItemAdmin, self).changelist_view(request=request, extra_context=extra_context)

Also check changelist_view parameters based on django version.

like image 68
itzMEonTV Avatar answered Feb 04 '26 00:02

itzMEonTV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!