Y
Y
YackSto2021-11-23 14:36:40
Django
YackSto, 2021-11-23 14:36:40

Django: How to update a field in a model when a front button is clicked?

I am building a web application for a pizzeria. You need to add an action: when you click on the "Order delivered" button, the order status should change to "Order completed". How to do it? It is necessary that when you click on the button, the status field in the order changes

models.py:
class OrderPizza(models.Model):
 
    STATUS_ACCEPT = 'Принят'
    STATUS_COOK = 'Готовится'
    STATUS_PREPARED = 'Приготовлен'
    STATUS_DELIVERED = 'Доставляется'
    STATUS_EXECUTE = 'Исполнен'
 
    STATUS_CHOISES = (
        (STATUS_ACCEPT, 'Принят'),
        (STATUS_COOK, 'Готовится'),
        (STATUS_PREPARED, 'Приготовлен'),
        (STATUS_DELIVERED, 'Доставляется'),
        (STATUS_EXECUTE, 'Исполнен')
    )
    id = models.AutoField(primary_key=True)
    date = models.DateField(verbose_name='Дата заказа', null=False, default = timezone.now())
    name = models.CharField(verbose_name='Имя заказчика', max_length=50)
    surname = models.CharField(verbose_name='Фамилия заказчика', max_length=50)
    phone_number = models.CharField(verbose_name='Номер телефона', max_length=10)
    adress = models.CharField(verbose_name='Адрес доставки', max_length=40)
    order = models.ManyToManyField(Pizza)
    courier = models.ForeignKey(Courier, on_delete=models.CASCADE)
    status = models.CharField(
        verbose_name='Статус', 
        max_length=12, 
        choices=STATUS_CHOISES, 
        default=STATUS_ACCEPT
        )
    
    def __str__(self):
        return ('Заказ от {0}  {1}').format(self.surname, self.date)
 
    class Meta():
        verbose_name = 'Заказ пиццы'
        verbose_name_plural = 'Заказы пиццы'  
 
class OrderPizzaWithPrice(models.Model):    
 
    order = models.ForeignKey(OrderPizza, on_delete=models.CASCADE)
    price = models.DecimalField(verbose_name='Стоимость заказа', default=0, max_digits = 10, decimal_places=2)
 
    def save(self, *args, **kwargs):
        self.price = sum([price.price for price in self.order.order.all()])       
        super(OrderPizzaWithPrice, self).save(*args, **kwargs)
 
    def __str__(self):
        return ('Заказ от {0}  {1}').format(self.order.surname, self.order.date)
 
    class Meta():
        verbose_name = 'Заказ пиццы со стоимостью'
        verbose_name_plural = 'Заказы пиццы со стоимостью'


views.py:

from django.shortcuts import render
 
from django.http import HttpResponse
from django.views.generic.base import RedirectView
 
from .models import OrderPizzaWithPrice, Product, Pizza ,Courier, OrderPizza, Technology_card
 
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
 
def index(request):
    return HttpResponse('Hello!')
 
class OrderView(ListView):
    model = OrderPizzaWithPrice
    template_name = 'mainapp/listOrder.html'
    context_object_name = "orders_list"
    ordering = ['-id']
 
    def get_context_data(self,*,object_list=None, **kwargs):
        context = super().get_context_data(**kwargs)
        context['orders_list'] = OrderPizzaWithPrice.objects.all()
        return context
 
class ProductView(ListView):
    model = Product
    template_name = 'mainapp/listProducts.html'
    context_object_name = "product_list"
    ordering = ['-id']
 
    def get_context_data(self,*,object_list=None, **kwargs):
        context = super().get_context_data(**kwargs)
        context['product_list'] = Product.objects.all()
        return context
 
    def upload(request):
        if request.method == 'POST':
            
            return RedirectView('home')


listOrder.html:

{% extends 'base.html' %}
{% block title %}Orders{% endblock %}
{% block content %}      
            
                    {% for i in orders_list %}
                    <table style="border:1px solid #000000">
                        <tr><td>Имя</td><td>{{i.order.name}}</td></tr>
                        <tr><td>Фамилия</td><td>{{i.order.surname}}</td></tr>
                        <tr><td>Телефон</td><td>{{i.order.phone_number}}</td></tr>
                        <tr><td>Адрес</td><td>{{i.order.adress}}</td></tr>
                        <tr><td>Заказ</td><td>
                            {% for n in i.order.order.all %}
                                {{n.title}}
                            {% endfor %}                            
                        </td></tr>
                        <tr><td>Стоимость</td><td>{{i.price}}</td></tr>
                        <tr><td>Курьер</td><td>{{i.order.courier}}</td></tr>
                        <tr><td>Статус</td><td>{{i.order.status}}</td></tr>
                        <tr><td>
                            <form method="post">
                                <button type="submit">Заказ доставлен</button>
                            </form>
                        </td><tr>
                    </table>
                    {% endfor %}        
{% endblock %}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Melnikov, 2021-11-23
@Mi11er

We send a POST request with the data to be updated. Updating =)
What can't you do?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question