N
N
Nikolai Vinogradov2016-07-06 10:29:34
Django
Nikolai Vinogradov, 2016-07-06 10:29:34

How to fix IndexError at /admin/auth/user/ list index out of range?

There are 2 models: customers(which contains the field user = m.ForeignKey(User, related_name="customers")) and userAdmin(class UserAdmin(NestedModelAdmin, DjangoUserAdmin)). I made a custom field that displays for each user a link to their orders. Code in app/models.py:

def orders_url(self):
return format_html(u"<a href='/admin/order/order/?q={0}'>Orders</a>", self.user.first_name)

Code in app/admin/admin_user.py model:
from myproject.customer.models import Customer
def orders_url(self, user):
    customer = user.customers.all()[0]
    return customer.orders_url()

If you go to the list of users with a search query (for example /admin/auth/user/?q=Nick), then everything goes well, the field is there, the link is there, redirects to the list of orders. But if I just go to the list of all users (/admin/auth/user/), then I get this error: IndexError at /admin/auth/user/ list index out of range. The Traceback highlights the following:
Error during template rendering
In template /home/vagrant/venv/local/lib/python2.7/site-packages/django/contrib/admin/templates/admin/change_list.html, error at line 91
list index out of range
91 {% result_list cl %}

path_to_project/customer/admin/user_admin.py in orders_url
                customer = user.customers.all()[0] 
▼ Local vars
Variable    Value
self       <myproject.customer.admin.user_admin.UserAdmin object at 0xa7e788c>
user       <User: >

Why is the user from self empty? and how to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikolai Vinogradov, 2016-07-06
@Kibastus

Solved with the following code:

def orders_url(self, user):
    customers = user.customers.all()
    return format_html(', '.join([customer.orders_url() for customer in customers]))

Now everything works without errors.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question