未添加以前的 ManytoMany 对象

Former ManytoMany object is not added

我想为航班添加一位新乘客,我使用模型来存储它。但是相反,在我提交表单后它完全没有变化,除了意外的 URL 变化:从 localhost:8000/flights/5localhost:8000/flights/5/book before after

def book(request, flight_id):
    if request.method == "POST":
        flight = Flight.objects.get(pk=flight_id)
        passenger = Passenger.objects.get(pk=int(request.POST["passenger"]))
        passenger.flights.add(flight)
        return HttpResponseRedirect(reverse("flight", args=(flight.id,)))
class Passenger(models.Model):
    first = models.CharField(max_length=64)
    last = models.CharField(max_length=64)
    flights = models.ManyToManyField(Flight, blank=True, related_name="passengers")

航班是另一个 class,顺便说一下。 还有我的 urlpatterns:

urlpatterns = [
    path("", views.index, name="index"),
    path("<int:flight_id>", views.flight, name="flight"),
    path("<int:flight_id>/book", views.flight, name="book")
]

知道为什么会出错吗?

如有任何帮助,我们将不胜感激。 非常感谢!

您必须更新 urlpatterns 以包含 views.book:

urlpatterns = [
    path("", views.index, name="index"),
    path("<int:flight_id>", views.flight, name="flight"),
    path("<int:flight_id>/book", views.book, name="book")
]