Home > OS >  Former ManytoMany object is not added
Former ManytoMany object is not added

Time:02-17

I want to add a new passenger to the flight, and I use models to store that. But instead, it had absolutely no change after I submit the form, except for the unexpected URL change: from localhost:8000/flights/5 to localhost: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")

Flight is another class, by the way. And there are my urlpatterns:

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

any idea why it's going wrong?

Any help would be much appreciated. Thanks a lot!

CodePudding user response:

update views.flight for 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")
]

CodePudding user response:

You have to update the urlpatterns to include the 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")
]
  • Related