TransWikia.com

How to update Order Status in Template if changed by Admin

Stack Overflow Asked by A_K on November 16, 2021

Hi I have a beginners question

I have an e-commerce project and I have BooleanField with different status for the orders. I want to be able to show user the Order Status after being changed from the admin.

Here is the models.py

class Order(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
    ref_code = models.CharField(max_length=20, blank=True, null=True)
    ordered = models.BooleanField(default=False)
    items = models.ManyToManyField(OrderItem)
    ordered_date = models.DateTimeField()
    out_for_delivery = models.BooleanField(default=False)
    received = models.BooleanField(default=False)

Here is the template:

            {% for order in orders %}
                    Order Reference: {{order.ref_code}} <br>
                    Ordered on: {{order.ordered_date}}<br>
                    Order Status:
                        {% if order is out_for_delivery %}
                    Order is out for delivery
                        {% else if order is received %}
                    Order is received
                        {% endif %}
            {% endfor %}

here is the views.py

class OrderList(LoginRequiredMixin, ListView):
    model = Order
    template_name = "user_orders.html"
    context_object_name = 'orders'
    paginate_by = 2
    ordering = ['-ordered_date']
    queryset = Order.objects.filter(ordered=True).order_by('-ordered_date')

    def get_queryset(self):
        return Order.objects.filter(user=self.request.user, ordered=True).order_by('-ordered_date')

Thank you all

One Answer

You have applied wrong if-else conditions:

Template

{% for order in orders %}
    Order Reference: {{order.ref_code}} <br>
    Ordered on: {{order.ordered_date}}<br>
    Order Status:
        {% if order.out_for_delivery %}
    Order is out for delivery
        {% elif order.received %}
    Order is received
        {% endif %}
{% endfor %}

Or I Would suggest not to take so many boolean fields for status. You can take a selection field for that

Model

status = models.CharField(max_length=50,choices=[('pending','Pending'),('ofd','Out For Delivery'),('recieved','Recieved')],default='pending')

so you can directly show this in a template like

{{order.get_status_display}}

Answered by Pruthvi Barot on November 16, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP