'Django - Cancel one delivery but when cancelling one it cancels all the deliveries
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" class="btn btn-danger"
name="update">Cancel</button>
<input type="hidden" value="{{ d.receipt_number }}"
name="receipt_number">
</form>
{% endif %}
Models:
Here is the list of deliveries:
I want to cancel one delivery and it automatically moves to the "Done/Cancelled Deliveries" page.
Solution 1:[1]
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()
Solution 2:[2]
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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Smile23 |
Solution 2 | Bartosz Stasiak |