Django使用zip_longest获取Withdrawal ID生成URL的错误排查
Django NoReverseMatch 错误排查与解决
错误原因分析
zip_longest 填充值类型不匹配
使用zip_longest(deposits, withdrawals, fillvalue='No Transaction')时,若存款和取款记录数量不一致,其中一方会被填充字符串'No Transaction'。模板中直接访问withdrawal.account、withdrawal.id等属性时,字符串无对应属性,导致取值为空,生成URL时传递空参数触发NoReverseMatch。模型字段引用错误
模板中使用withdrawal.withdrawal_id,但Witdrawal模型未定义该字段,正确主键字段为Django默认生成的id。URL路径拼写错误
URL配置中路径为witdrawal/slip/,存在拼写错误(少字母h,应为withdrawal),会导致路由匹配异常。
解决方案
1. 修正填充值类型
将zip_longest的填充值改为None,便于模板判断是否为有效记录:
# 视图代码修改 from itertools import zip_longest def account_statement(request, id): # ... 其他逻辑不变 context = { "deposits_and_withdrawals": zip_longest(deposits, withdrawals, fillvalue=None), }
2. 模板增加空值判断
渲染取款记录前先判断是否为有效对象,避免访问无效属性:
{% for deposit, withdrawal in deposits_and_withdrawals %} <!-- 存款记录渲染 --> <tr> <td style="background-color:rgba(231, 232, 233, 0.919); color:blue;">Deposit - </td> <td style="background-color:rgba(231, 232, 233, 0.919)">{{ deposit.acct }}</td> <td style="background-color:rgba(231, 232, 233, 0.919)">{{ deposit.transID }}</td> <td style="background-color:rgba(231, 232, 233, 0.919)">N{{ deposit.deposit_amount | intcomma }}</td> <td style="background-color:rgba(231, 232, 233, 0.919)">{{ deposit.date | naturaltime }}</td> <th scope="row" style="background-color:rgba(231, 232, 233, 0.919)"> <a class="btn btn-success btn-sm" href="{% url 'deposit-slip' deposit.id %}">Slip</a> </th> </tr> <!-- 取款记录渲染(增加空值判断) --> {% if withdrawal %} <tr style="color: red;"> <td>Withdrawal - </td> <td>{{ withdrawal.account.surname }}</td> <td>{{ withdrawal.transID }}</td> <td>N{{ withdrawal.withdrawal_amount | intcomma }}</td> <td>{{ withdrawal.date | naturaltime }}</td> <th scope="row"> <a class="btn btn-success btn-sm" href="{% url 'withdrawal-slip' withdrawal.id %}">Slip</a> </th> </tr> {% else %} <tr style="color: red;"> <td colspan="6">No Withdrawal Transaction</td> </tr> {% endif %} {% endfor %}
3. 修正URL路径拼写
修改URL配置中的拼写错误:
urlpatterns = [ path('withdrawal/slip/<int:id>/', user_view.withdrawal_slip, name='withdrawal-slip'), ]
4. 校验关联查询逻辑
确认withdrawals = Witdrawal.objects.filter(account__id=customerID)中,customerID确实是Profile模型的主键(因Witdrawal的account外键关联Profile),避免查询不到有效取款记录。
内容的提问来源于stack exchange,提问作者apollos
相关产品推荐
相关产品推荐

