这是我的delete_category函数:
def delete_category(request, id):
user = request.user
category = Category.objects.get(pk=id)
category.user.remove(user)
return HttpResponseRedirect(reverse('auth_profile', args=[user.username]))
这是我的category_detail函数:
def category_detail(request, category_name):
user = request.user
category = Category.objects.filter(name=category_name, user__username=user)[0]
return render_to_response("category_detail.html", { "category":category}, context_instance=RequestContext(request))
这是category_detail.html:
<p>{{category.name}}</p>
<a href="{% url 'delete_category' category.id %}">delete</a>
如果我有多个类别,我可以在单击删除链接时删除。但如果我只有一个类别,我会收到此错误:
list index out of range
答案 0 :(得分:3)
更改
category = Category.objects.filter(name=category_name, user__username=user)[0]
通过
categories = Category.objects.filter(name=category_name, user__username=user)
category = None
if categories:
category = categories[0]
另请参阅如何使用QuerySet对象here
正常工作答案 1 :(得分:1)
您的代码有点难以理解,我怀疑这不是完全代码,但没关系。
列表索引超出范围是指您指定的...[0]
。
您可能想要重写您已经更好地处理零类别的内容,但快速修复是:
try:
category = Category.objects.filter(name=category_name, user__username=user)[0]
except:
category = None
...