Search code examples
djangodjango-viewsdjango-templatesdjango-urls

how to render URL patterns in Django with multiple apps


I am trying to build a booking system, using Django. I have multiple apps and rendering the urls patterns has been difficult to understand and i have found the documentation little help when you have multiple apps.

Here is my core app urls:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('review.urls'), name='review_urls'),
    path('accounts/', include('allauth.urls')),
    path('bookings/', include('booking.urls'), name='booking_urls'),

]

The booking app urls:

urlpatterns = [
    path('booking', views.customer_booking, name='booking'),
    path('display_booking', views.display_booking, name='display_booking'),
    path('edit_booking/<booking_id>',
         views.edit_booking, name='edit_booking'),

]

I am trying to render my edit_booking view:

def edit_booking(request, booking_id):
    booking = get_object_or_404(Booking, id=booking_id)
    if request.method == "POST":
        form = BookingForm(request.POST, instance=booking)
        if form.is_valid():
            form.save()
            return redirect('display_booking')
    form = BookingForm(instance=booking)
    context = {
        'form': form
    }
    return render(request, 'edit_booking.html', context)

where it is being called:

<a href="/edit_booking/{{ booking.id }}"> <button>Edit</button></a>

I tried adding bookings/ into my edit button but this is requesting a page with bookings/bookings/edit_booking/7. without it, it is just requesting the endpoint edit_booking/7


Solution

  • You need to use the url template tag

    <a href="{% url 'edit_booking' booking.id %}"> <button>Edit</button></a>