Home > Software design >  Django: Changing the model field in the database when the button is clicked
Django: Changing the model field in the database when the button is clicked

Time:11-18

I am creating 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:
from django.db import models
from django.db.models.fields import DecimalField, NullBooleanField
import decimal
from django.utils import timezone
from django.db.models.signals import pre_save
from django.dispatch import receiver
 
class Product(models.Model):
 
    title = models.CharField(verbose_name='Название продукции', max_length=100)
    count = models.DecimalField(verbose_name='Кол-во на складе', max_digits = 10, decimal_places=4)
    price = models.DecimalField(verbose_name='Цена', max_digits = 10, decimal_places=4)
    date = models.DateField(verbose_name='Дата обновления', default=timezone.now())
    def __str__(self):
        return self.title
 
    class Meta():
        verbose_name = 'Продукты'
        verbose_name_plural = 'Продукция'   
 
class Technology_card(models.Model):
 
    title = models.TextField(verbose_name='Название ТК',default='Технологическая карта для пиццы')
    pizza_box = models.DecimalField(verbose_name='Коробки пиццы',max_digits = 10, decimal_places=4, default=1)
    napkins = models.DecimalField(verbose_name='Салфетки',max_digits = 10, decimal_places=4, default=6)
    dough = models.DecimalField(verbose_name='Тесто',max_digits = 10, decimal_places=4, default=0)
    flour = models.DecimalField(verbose_name='Мука',max_digits = 10, decimal_places=4, default=0)
    tomato_sauce = models.DecimalField(verbose_name='Соус томатный',max_digits = 10, decimal_places=4, default=0)
    cream_sauce = models.DecimalField(verbose_name='Соус сливочный', max_digits = 10, decimal_places=4, default=0)
    olive_oil = models.DecimalField(verbose_name='Оливковое масло', max_digits = 10, decimal_places=4, default=0)
    mozzarella_cheese = models.DecimalField(verbose_name='Сыр Моцарелла', max_digits = 10, decimal_places=4, default=0)
    parmesan_cheese = models.DecimalField(verbose_name='Сыр Пармезан', max_digits = 10, decimal_places=4, default=0)  
    dor_blue_cheese = models.DecimalField(verbose_name='Сыр Дор Блю', max_digits = 10, decimal_places=4, default=0)
    bacon = models.DecimalField(verbose_name='Бекон', max_digits = 10, decimal_places=4, default=0)
    ham = models.DecimalField(verbose_name='Ветчина', max_digits = 10, decimal_places=4, default=0)
    pineapple = models.DecimalField(verbose_name='Ананас', max_digits = 10, decimal_places=4, default=0)
    cervelat = models.DecimalField(verbose_name='Сервелат', max_digits = 10, decimal_places=4, default=0)
    pepperoni = models.DecimalField(verbose_name='Пепперони', max_digits = 10, decimal_places=4, default=0)
    pickled_chicken = models.DecimalField(verbose_name='Курица маринованная', max_digits = 10, decimal_places=4, default=0)
    tomatoes = models.DecimalField(verbose_name='Томаты', max_digits = 10, decimal_places=4, default=0)
    champignons = models.DecimalField(verbose_name='Шампиньоны', max_digits = 10, decimal_places=4, default=0)
    italian_herbs = models.DecimalField(verbose_name='Итальянские травы', max_digits = 10, decimal_places=4, default=0)
    green_onion = models.DecimalField(verbose_name='Лук зеленый', max_digits = 10, decimal_places=4, default=0)
    garlic_butter_box = models.DecimalField(verbose_name='Масло чесночное бокс', max_digits = 10, decimal_places=4, default=1)
    pepper_oil_box = models.DecimalField(verbose_name='Масло перцовое бокс', max_digits = 10, decimal_places=4, default=1)
 
    def __str__(self):
        return self.title
 
    class Meta():
        verbose_name = 'Технологическая карта'
        verbose_name_plural = 'Технологические карты' 
 
class Pizza(models.Model):
    
    title = models.CharField(verbose_name='Название пиццы', max_length=100)
    technology_card = models.ForeignKey(Technology_card, on_delete=models.CASCADE)
    time_production = models.PositiveIntegerField(verbose_name='Время изготовления', default=10)
    time_baking_time = models.PositiveIntegerField(verbose_name='Время выпекания', default=10)  
    price = models.DecimalField(verbose_name='Цена', max_digits = 10, decimal_places=2, default = 0)
 
    def save(self, *args, **kwargs):
        price = 100
        pr = []
        for i in range(1,23):
            pr.append(Product.objects.get(id = i))
        pi1 = pr[0].price * self.technology_card.pizza_box
        pi2 = pr[1].price * self.technology_card.napkins
        pi3 = pr[2].price * self.technology_card.dough
        pi4 = pr[3].price * self.technology_card.flour
        pi5 = pr[4].price * self.technology_card.tomato_sauce
        pi6 = pr[5].price * self.technology_card.cream_sauce
        pi7 = pr[6].price * self.technology_card.olive_oil
        pi8 = pr[7].price * self.technology_card.mozzarella_cheese
        pi9 = pr[8].price * self.technology_card.parmesan_cheese
        pi10 = pr[9].price * self.technology_card.dor_blue_cheese
        pi11 = pr[10].price * self.technology_card.bacon
        pi12 = pr[11].price * self.technology_card.ham
        pi13 = pr[12].price * self.technology_card.pineapple
        pi14 = pr[13].price * self.technology_card.cervelat
        pi15 = pr[14].price * self.technology_card.pepperoni
        pi16 = pr[15].price * self.technology_card.pickled_chicken
        pi17 = pr[16].price * self.technology_card.tomatoes
        pi18 = pr[17].price * self.technology_card.champignons
        pi19 = pr[18].price * self.technology_card.italian_herbs
        pi20 = pr[19].price * self.technology_card.green_onion
        pi21 = pr[20].price * self.technology_card.garlic_butter_box
        pi22 = pr[21].price * self.technology_card.pepper_oil_box
        price = pi1   pi2   pi3   pi4   pi5   pi6   pi7   pi8   pi9   pi10   pi11   pi12   pi13   pi14   pi15   pi16   pi17   pi18   pi19   pi20   pi21   pi22
        coff = decimal.Decimal(1.50)
        self.price = (price * coff).quantize(decimal.Decimal("1.00"))
        super(Pizza, self).save(*args, **kwargs)
 
    def __str__(self):
        return self.title
 
    class Meta():
        verbose_name = 'Пицца'
        verbose_name_plural = 'Пицца'
 
class Courier(models.Model):
    name = models.CharField(verbose_name='Имя курьера', max_length=50)
    surname = models.CharField(verbose_name='Фамилия курьера', max_length=50)
    patronymic = models.CharField(verbose_name='Отчество курьера', max_length=50)
    count_order = models.PositiveIntegerField(verbose_name='Кол-во выполненых заказов', default=0)
 
    def __str__(self):
        return (self.surname   " "   self.name   " "   self.patronymic)
    
    class Meta():
        verbose_name = 'Курьер'
        verbose_name_plural = 'Курьеры'    
 
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 %}

CodePudding user response:

This is a demo of order tracker :--

def order_tracker(request):
    if request.method=="POST":
        orderId = request.POST.get('orderId', '')
        try:
            order=OrderPizza.objects.get(pk=orderId)
            if OrderPizza.status == 'processing':
                OrderPizza.status = 'scheduled'
                order.save()
            return JsonResponse({'status' : OrderPizza.status})
        except: OrderPizza.DoesNotExist:
            return JsonResponse({})
    return render(request,"your_page.html")

CodePudding user response:

Modify your form part

<form method="post" action="{% url 'pizza_order_delivered_url' %}">
     <input type="hidden" name= "order_id" value="{{ i.pk }}">
     <button type="submit">Заказ доставлен</button>
 </form>

View part

def pizza_order_delived(request):
    if request.method=="POST":
        order_id = request.POST.get('order_id', 0)
        try:
            order=OrderPizza.objects.get(pk=order_id)
            order.status = 'Доставляется' # STATUS_DELIVERED
            order.save()
    
        except OrderPizza.DoesNotExist:
            pass
        return HttpResponseRedirect(reverse('your_order_list_url'))
    else:
        # use message to display error to user
        return HttpResponseRedirect(reverse('your_order_list_url'))

CodePudding user response:

You have to make a post request to your OrderView. For example,

class OrderView(ListView):
    model = OrderPizzaWithPrice
    template_name = 'mainapp/listOrder.html'
    context_object_name = "orders_list"
    ordering = ['-id']
    
    def post(self,request):
        order = get_object_or_404(OrderPizza, id=request.POST.get('order_id'))
        order.status = "Order completed"
        order.save()
        context = self.get_context_data()
        return render(request, template_name, context)
        

In your listOrder.html:

<form method="post" action="order_view_url">
  <input type="hidden" name="order_id" value="{{i.order.order.id}}"/>
  <button type="submit">Заказ доставлен</button>
</form>
  • Related