[Fixed]-Django view redirects to URL it shouldn't

1👍

“.”, which you used as the action of the form, is interpreted by browsers as “the base of the current path directory”. Since you have not used a trailing slash in your /edit URL, the browser submits the form to the nearest base, ie /booking/24.

You should always use a trailing slash:

url(r'^booking/create/$', create_booking, name="create-booking"),
url(r'^booking/$', booking_list, name="booking-list"),
url(r'^booking/(?P<pk>\d+)/$', booking_detail, name="booking-detail"),
url(r'^booking/(?P<pk>\d+)/edit/$', edit_booking, name="edit-booking"),

0👍

You need to check for the request method otherwise it will redirect on initial form rendering because django uses the same view for initial rendering and submitting the form.

if request.method == 'POST':
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        return HttpResponseRedirect(instance.get_absolute_url())       
    elif form.errors:
        messages.error(request,"There was a problem, please try again")
else:
    context = {
        "form": form,
    }
    return render(request,'booking_form.html', context)

Leave a comment