gpt4 book ai didi

python - django-python : NoReverseMatch issue: what argument should I give it?

转载 作者:太空宇宙 更新时间:2023-11-03 16:15:21 25 4
gpt4 key购买 nike

我有以下观点:

def default_detail (request, equipment_id):
equipment = Equipment.objects.get(id = equipment_id)
context = {'equipment' : equipment}
return render(request, 'calbase/default_detail.html', context)


def default_add_cal (request, equipment_id):
equipment = get_object_or_404(Equipment, id = equipment_id)
EquipmentInlineFormSet = inlineformset_factory(Equipment, Calibration, fields = ('cal_by', 'cal_date', 'notes'), extra = 1, )
if request.method == "POST":
if 'calibration' in request.POST:
formset = EquipmentInlineFormSet(request.POST, request.FILES, instance=equipment)
if formset.is_valid():
return HttpResponseRedirect(reverse('calbase:default_detail', args=(equipment_id)))
else:
formset = EquipmentInlineFormSet(instance=equipment)
return render(request, 'calbase/default_detail_cal.html', {'formset' : formset, 'equipment' : equipment})

网址是这样的:

urlpatterns = [
url(r'^$', views.default, name = 'default'),
url(r'^default/(?P<equipment_id>[0-9]+)/$', views.default_detail, name = 'default_detail'),
url(r'^default/new/$', views.default_new, name = 'default_new'),
url(r'^default/(?P<equipment_id>[0-9]+)/cal/$', views.default_add_cal, name = 'default_add_cal'),
]

default_add_cal、default_detail_cal.html 的模板如下:

{% block content %}
<form method="POST" action = "{% url 'calbase:default_add_cal' equipment.id %}">{% csrf_token %}
{{ formset }}
<button type="submit" class="save btn btn-default" name = "calibration">Save</button>
</form>

<a href="{% url 'calbase:default' %}">Back?</a>
{% endblock %}

所以校准是设备的外键:一个设备可以有多个校准,这里我尝试使用内联表单集让用户向设备添加校准。问题是我得到了这个:

NoReverseMatch at /calbase/default/41/cal/ Reverse for 'default_detail' with arguments '('4', '1')' and keyword arguments '{}' not found. 1 pattern(s) tried: ['calbase/default/(?P[0-9]+)/$']

令我困惑的是,例如,对于设备 id =41,当我这样做时

return HttpResponseRedirect(reverse('calbase:default_detail', args=(equipment_id)))

实际传递的参数是 '('4', '1')' 而不是 41。怎么会这样呢?我应该如何解决这个问题?谢谢

最佳答案

您应该将参数作为元组传递。这将使 args 成为一个可迭代对象,其中 equipment_id 作为参数之一:

args=(equipment_id,‌​)
# ^

这些分组括号不会使参数成为元组:

>>> args = (42)
>>> type(args)
<class 'int'>
>>>
>>> args = (42,)
>>> type(args)
<class 'tuple'>

即使没有括号也能工作:

>>> args = 42,
>>> type(args)
<class 'tuple'>

关于python - django-python : NoReverseMatch issue: what argument should I give it?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38982944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com