反向 'chi_tiet_hop_dong' 关键字参数 '{'so_hd': ''}' 未找到。尝试了 1 种模式:['chi_tiet_hop_dong/(?P<so_hd>[^/]+)/$']

Reverse for 'chi_tiet_hop_dong' with keyword arguments '{'so_hd': ''}' not found. 1 pattern(s) tried: ['chi_tiet_hop_dong/(?P<so_hd>[^/]+)/$']

我有这个错误的问题

我的模型。

class testimport(models.Model):
    id=models.AutoField(primary_key=True)
    so_hd=models.CharField( max_length=50, unique=True)
    ten_kh=models.CharField( max_length=500)

    def get_absolute_url(self):
        return "/chi_tiet_hop_dong/%s/" % self.so_hd

class report(models.Model):
     id=models.AutoField(primary_key=True)
     so_hd=models.ForeignKey(testimport, on_delete=models.CASCADE, to_field="so_hd")

如果我不在模型报告中使用 to_field="so_hd",则不会出现错误,但我需要在 link 中使用 "so_hd"在不使用 to_field

的情况下,模型测试导入不是模型测试导入中的“id 主键”

我的看法:

def chi_tiet_hop_dong(request,so_hd):
    contract=testimport.objects.filter(so_hd=so_hd)
    print("số hợp đồng trong def chi tiết hợp đồng",so_hd)
    request.session["save_so_hd"]=json.loads(json.dumps(so_hd))
    lst_contract=request.session["get_contract_detail"]
    
    try:
        the_next = lst_contract[lst_contract.index(so_hd) + 1]
        print("the next",the_next)
    except:
        the_next=None

    try:
        the_prev=lst_contract[lst_contract.index(so_hd) - 1]
        print("the prev",the_prev)
    except:
        the_prev=None

    baocao=report.objects.filter(so_hd=so_hd)

    form=AddReportForm()
    
    
    return render(request, "caller_template/contract_detail.html", {"contract":contract,"the_next":the_next,"the_prev":the_prev,"baocao":baocao,"form":form})

我检查打印出the_next、the_prev和so_hd,没问题

我的url:

path('chi_tiet_hop_dong/<str:so_hd>/', CallerViews.chi_tiet_hop_dong, name="chi_tiet_hop_dong"),

请帮帮我

我认为你应该尝试按 id 而不是 so_hd 进行过滤,这样你就可以在你的视图中这样做:


def chi_tiet_hop_dong(request,so_hd):
    contract=testimport.objects.filter(id=so_hd)
    print("số hợp đồng trong def chi tiết hợp đồng",so_hd)
    request.session["save_so_hd"]=json.loads(json.dumps(so_hd))
    lst_contract=request.session["get_contract_detail"]
    
    try:
        the_next = lst_contract[lst_contract.index(so_hd) + 1]
        print("the next",the_next)
    except:
        the_next=None

    try:
        the_prev=lst_contract[lst_contract.index(so_hd) - 1]
        print("the prev",the_prev)
    except:
        the_prev=None

    baocao=report.objects.filter(id=so_hd)

    form=AddReportForm()
    
    
    return render(request, "caller_template/contract_detail.html", {"contract":contract,"the_next":the_next,"the_prev":the_prev,"baocao":baocao,"form":form})