* 后的 _reverse_with_prefix() 参数必须是可迭代的,而不是 int [英] _reverse_with_prefix() argument after * must be an iterable, not int

查看:18
本文介绍了* 后的 _reverse_with_prefix() 参数必须是可迭代的,而不是 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我过去曾多次使用 Django 的 reverse,但今天遇到这个错误,这似乎不够直观,无法调试:

I have used Django's reverse multiple times in the past but getting this error today which doesn't seem intuitive enough to debug:

TypeError: _reverse_with_prefix() argument after * must be an iterable, not int

这是我使用它的视图:

from django.urls import reverse

...
...
def show_scores_url(self, obj):
    scores_url = reverse('get_scores', args=(obj.pk))
    return format_html('<a href="' + scores_url + '">Scores</a>')

...
...

推荐答案

这个 评论,在 args 元组末尾放一个逗号可以修复它.

As mentioned in this comment, putting a comma at the end of the args tuple fixes it.

scores_url = reverse('get_scores', args=(obj.pk,))

(如 this SO answer 中所述,单项元组需要尾随逗号以消除定义元组的歧义括号括起来的表达式)

(As mentioned in this SO answer, trailing comma is required for single-item tuples to disambiguate defining a tuple from an expression surrounded by parentheses)

或者,如 docs 中所述,使用列表会工作正常:

Alternatively, as mentioned in the docs, using a list would work fine:

scores_url = reverse('get_scores', args=[obj.pk])

这篇关于* 后的 _reverse_with_prefix() 参数必须是可迭代的,而不是 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆