为什么会出现NoReverseMatch错误,该如何解决?

时间:2020-03-31 05:09:39

标签: django django-urls

这是我的代码:

views.py

def book(request, flight_id):
    try:
        passenger_id = int(request.POST["passenger"])
        passenger = Passengers.objects.get(pk=passenger_id)
        flight = Flights.objects.get(pk=flight_id)
    except KeyError:
        return render(request, 'flights/error.html', {'message':'No Selection'})
    except Flights.DoesNotExist:
        return render(request, 'flights/error.html', {'message':'No Flight'})
    except Passengers.DoesNotExist:
        return render(request, 'flights/error.html', {'message': 'No Passengers'})

    passenger.flights.add(flight)
    return HttpResponseRedirect(reverse('flight', args=(flight_id,)))

模板

<h2>Add a Passenger</h2>
{% if non_passengers %}
<form action="{% url 'book' flight.id %}" method="post">
    <select name="passenger">
    {% for passenger in non_passengers %}
    <option value="passenger.id">{{ passenger }}</option>
    {% endfor %}
    </select>
    <input type="submit" value="Book Flight"/>

</form>
{% else %}
   <div>No Passengers to add</div>
{% endif %}

urls.py

   path('', views.index, name='index'),
   path('<int:flight_id>', views.flight, name='flight'),
   path('<int:flight_id>/book', views.book, name='book')

它向我显示了这样的错误:

NoReverseMatch在/ 1 找不到带有参数'(',)'的'book'反向字符。尝试了1种模式:['(?P [0-9] +)/ book $']

0 个答案:

没有答案