这是我的第一个 Django 项目,我真的很挣扎。这是一个简单的预订应用程序,登录用户所在的页面上有一个预订表格和当前预订列表。我可以使页面正常工作并进行预订,但表单中的信息未清除,如果刷新页面,则会再次进行预订。为了解决这个问题,我想我需要在预订后重定向到成功页面。当我尝试这样做时,我收到“NoReverseMatch”错误,并被告知它“不是有效的视图函数或模式名称。”
以下是 booking.urls.py 的 url 模式:
from django.urls import path
from . import views
urlpatterns = [
path("", views.home, name='home'),
path("booking/", views.booking, name='booking'),
path('my_bookings/', views.my_bookings, name='my_bookings'),
path('edit_booking/<int:booking_id>', views.edit_booking, name='edit_booking'),
path('delete_booking/<int:booking_id>', views.delete_booking, name='delete_booking'),
path('success_booking/', views.success_booking, name='success_booking'),
]
以下是 booking.views.py 的部分内容:
def my_bookings(request):
bookings = Booking.objects.filter(user=request.user)
booking_form = BookingForm()
if request.method == "POST":
booking_form = BookingForm(data=request.POST)
if booking_form.is_valid():
booking = booking_form.save(commit=False)
booking.user = request.user
booking.save()
return HttpResponseRedirect(reverse('/booking_delete/'))
return render(
request,
"booking/booking_list.html",
{
'booking_form' : booking_form,
'bookings': bookings,
},
)
这是 booking_list.html 中处理提交按钮的片段:
<div class="col-md-4 mb-4 mt-3">
<div>
{% if user.is_authenticated %}
<form id="bookingForm" method="post"
style="margin-top: 1.3em;">
{{ booking_form | crispy }}
{% csrf_token %}
<button id="BookingButton" type="submit"
class="btn btn-lg btn-light">Make A Booking</button>
<!-- <a class="btn btn-light btn-edit" href="{% url 'my_bookings' %}">Make Booking</a> -->
</form>
{% else %}
<p>Log in to make a booking</p>
{% endif %}
</div>
我知道我不了解这一切是如何运作的。我尝试更改 urls 文件并使用 DTL 作为提交按钮。我在 HttpResponseRedirect() 函数中尝试了不同的参数,但我真的迷失了!!!
此行有 2 个问题
return HttpResponseRedirect(reverse('/booking_delete/'))
更新此行代码应该可以工作
from django.urls import reverse
return redirect(reverse('booking_delete'))