我有2个模型:客户(包含user = m.ForeignKey(User,related_name =" customers"))和UserAdmin(UserAdmin类(NestedModelAdmin,DjangoUserAdmin))。我想添加到用户字段,它为每个用户生成订单链接:在app / models.py中我写了这段代码:
def orders_url(self):
return format_html(u"<a href='/admin/order/order/?q={0}'>Orders</a>", self.user.first_name)
在app / admin / user_admin.py中我有这段代码:
from myproject.customer.models import Customer
def orders_url(self, user):
customer = user.customers.all()[0]
return customer.orders_url()
当我尝试搜索某个用户时(例如/ admin / auth / user /?q = Nick),一切顺利,它会生成Nick的订单链接,但当我进入/ admin / auth / user /,我看到这个错误:/ admin / auth / user /中的IndexError 列表索引超出范围。 跟踪链接到下一个代码:
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: >
忘记了这条消息:
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 %}
如何更改?
答案 0 :(得分:0)
通过更改user_admin.py文件中的最后一行orders_url方法来解决问题:
def orders_url(self, user):
customers = user.customers.all()
return format_html(', '.join([customer.orders_url() for customer in customers]))
现在一切正常。