Django中NoReverseMatch异常错误的一个原因

Django中NoReverseMatch异常错误的一个原因_第1张图片今天遇到一个错误,截图如上:

分析原因发现因为在程序中需要用到typeid这个变量的值,但是程序发现没有typeid的值,所以报错。

发现问题是出在views.py中,出错前的程序如下:

def market_with_params(request, typeid, childcid):
    foodtypes = FoodType.objects.all()
    goods_list = Goods.objects.filter(categoryid=typeid).filter(childcid=childcid)
    foodtype= foodtypes.get(typeid=typeid)
    foodtypechildnames = foodtype.childtypenames
    foodtypechildname_list = foodtypechildnames.split("#")
    foodtype_childname_list = []
    for foodtypechildname in foodtypechildname_list:
        foodtype_childname_list.append(foodtypechildname.split(":"))
    print(foodtype_childname_list)
    data = {
        'title': '闪购',
        'foodtypes': foodtypes,
        'goods_list': goods_list,
        'foodtype_childname_list': foodtype_childname_list,
         }
    return render(request, 'main/market.html', context=data)

这个程序没有把typeid的值传给要渲染的market.html这个网页。因此做了以下修改:

def market_with_params(request, typeid, childcid):
    foodtypes = FoodType.objects.all()
    goods_list = Goods.objects.filter(categoryid=typeid).filter(childcid=childcid)
    foodtype= foodtypes.get(typeid=typeid)
    print(foodtype)
    foodtypechildnames = foodtype.childtypenames
    print(foodtypechildnames)
    foodtypechildname_list = foodtypechildnames.split("#")
    print(foodtypechildname_list)
    foodtype_childname_list = []
    for foodtypechildname in foodtypechildname_list:
        foodtype_childname_list.append(foodtypechildname.split(":"))
    print(foodtype_childname_list)
    data = {
        'title': '闪购',
        'foodtypes': foodtypes,
        'goods_list': goods_list,
        'foodtype_childname_list': foodtype_childname_list,
        'typeid': int(typeid),   #####加上这一行
    }
    return render(request, 'main/market.html', context=data)

把这行加上以后,typeid的内容就作为数据字典从这个函数传给了market.html。这样网页在找这个值时就有内容了。

总结:在渲染网页时,所有要用到的数据都要通过数据字典context传送给网页,不能缺少内容。

 

 

你可能感兴趣的:(Django中NoReverseMatch异常错误的一个原因)