/judge/judge-timeslot.html中的NoReverseMatch反向找不到带参数'('',)'的'sub'

时间:2018-01-11 13:58:29

标签: python django

运行Django 2.0.1。得到以下错误:

NoReverseMatch at /judge/judge-timeslot.html Reverse for 'sub' 
    with arguments '('',)' not found. 
1 pattern(s) tried: ['judge\\/(?P<choice_id>[0-9]+)$']

Request Method: GET  
Django Version: 2.0.1  
Exception Type: NoReverseMatch

urls.py:

from django.urls import path
from django.conf.urls import url
from . import views

app_name = 'judge'
urlpatterns = [
    path('judge-home.html', views.index, name='index'),
    path('judge-score.html', views.score, name='score'),
    path('judge-timeslot.html', views.timeslots, name='timeslots'),
    path('results.html', views.results, name='results'),
    path('<int:choice_id>', views.sub, name='sub'),
]

views.py中的子视图:

def sub(request, choice_id):
template = loader.get_template("judge/judge-timeslot.html")
c = get_object_or_404(Choice, pk=choice_id)

try:
    selected_choice = c.choice_set.getlist(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
    # Redisplay the question voting form.
    return render(request, template, {
        'choice': c,
        'error_message': "You didn't select a choice.",
    })
else:
    # selected_choice.votes += 1
    selected_choice.save()
    # Always return an HttpResponseRedirect after successfully dealing
    # with POST data. This prevents data from being posted twice if a
    # user hits the Back button.
    return HttpResponseRedirect(reverse('judge/judge-timeslot.html', args=(c.id,)))

这是法官-timeslot.html:

<form action="{% url 'judge:sub' choice.id %}" method="post">
    {% csrf_token %}
    <table class="table table--bordered table--highlight">
        <tbody>
            {% for slot in slots %}
            <tr>
                <td>
                    <label class="checkbox">
                        <input type="checkbox", name="choice" id="choice {{forloop.counter}}"
                        value="{{choice.id}}"/>
                        <span class="checkbox__input"></span>
                    </label>
                </td>
                <td>{{slot}}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
    <button class="btn btn--primary">Select</button>
</form>

指的是这一行:

<form action="{% url 'judge:sub' choice.id %}" method="post">

但无论我在urls.py中改变什么似乎都没有用。 有人能告诉我这是什么问题吗?

1 个答案:

答案 0 :(得分:1)

问题在于:

{% url 'judge:sub' choice.id %}

您的choice.id给出空结果

这是正常的:你在这里做了一个循环{% for slot in slots %}所以这是你应该使用的变量slot,而不是choice ...尝试使用slot.id代替choice.id

所以Django试图寻找一个名为“sub”的视图,它没有任何参数,他看到了一个:path('<int:choice_id>', views.sub, name='sub'),(这正是你的错误告诉你的)

模板调试注意事项:尝试显示slot中的内容

{% if slot %}
    Slot is: {{ slot }}
{% else %}
    Slot is empty!
{% endif %}

同样的选择,请将它放在“form”代码之前:

{% if choice %}
    Choice is: {{ choice }}
{% else %}
    Choice is empty!
{% endif %}

除此之外注意:如果您是Django的新手,请使用PyCharm(专业版(您可以免费使用30天),也可以使用社区免费版)并且您可以在模板文件中创建断点。非常有用。