I'm trying to cancel one "posted" delivery when the user clicks on the button "cancel", but it cancels all the posted deliveries below is the views.py
def current_delivery_page(request):
deliveries = Delivery.objects.filter(
restaurant = request.user.restaurant,
status_of_delivery__in=[
Delivery.DELIVERY_DELIVERING,
Delivery.DELIVERY_POSTED
]
)
delivery = Delivery.objects.all()
for a in delivery:
if request.method == 'POST' and request.POST['receipt_number']:
a.status_of_delivery = Delivery.DELIVERY_CANCELLED
a.save()
return render(request, 'restaurant/deliveries.html',
{
"deliveries": deliveries
})
{% if d.status_of_delivery == 'posted' %}
<form method="POST">
{% csrf_token %}
<button type="submit"
name="update">Cancel</button>
<input type="hidden" value="{{ d.receipt_number }}"
name="receipt_number">
</form>
{% endif %}
Here is the list of deliveries
I want to cancel one delivery and it automatically moves to the "Done/Cancelled Deliveries" page. Any help is appreciated, thanks.
CodePudding user response:
You should check if receipt_numer
from POST is equal to delivery instance receipt_number
for a in delivery:
if request.method == 'POST' and request.POST['receipt_number'] == a.receipt_number:
a.status_of_delivery = Delivery.DELIVERY_CANCELLED
a.save()
CodePudding user response:
you are looping through all Delivery
instances in the database and setting all their status to DELIVERY_CANCELED
in your for a in delivery
loop.
You need to use Delivery.objects.get(pk=request.POST.get('receipt_number'))
to fetch the delivery instance you need and then set its status to canceled. You could do something like this:
if request.method == 'POST':
delivery = get_object_or_404(Delivery, pk=request.POST.get('receipt_number'))
if delivery:
delivery.status_of_delivery = Delivery.DELIVERY_CANCELED
delivery.save()