简体   繁体   中英

Calculate total price from selected menu

I created a restaurant web using django frameworks. so i have a problem when i want to calculate all the menu prices are selected.

This is the simple Flowchart:

Login → user selecting customer → create customer order → billing but i not yet create the billing

here this my models.py

from django.db import models
from django.contrib.auth.models import User


class Menu(models.Model):
    name = models.CharField(max_length=255)
    price = models.FloatField()

    def __str__(self):
        return self.name + ', Rp ' + str(self.price) + '00'


class Customer(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(default='', max_length=255)
    gender = models.CharField(max_length=255)
    phone = models.CharField(max_length=255)
    address = models.TextField()

    def __str__(self):
        return self.name + ', phone = ' + self.phone

    def absolute_url(self):
        return self.slug


class Order(models.Model):
    menu = models.ManyToManyField(Menu, related_name='order')
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    total_prc = models.FloatField()
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.customer + ', total price = ' + self.total_prc


class Transaction(models.Model):
    order = models.ForeignKey(Order, on_delete=models.CASCADE)
    total = models.FloatField()
    paid = models.FloatField()

    def __str__(self):
        return self.order

so the menu and order models that i've been create with many to many relationship

then form.py for the create customer order

menu_choices = Menu.objects.all().values_list('pk', 'name')
menu_choices_list = []

for menu in menu_choices:
    menu_choices_list.append(menu)


class CreateOrder(forms.ModelForm):
    class Meta:
        model = Order
        fields = ('menu',)

        widgets = {
            'menu': forms.CheckboxSelectMultiple(choices=menu_choices_list)
        }

in the views.py i use generic class based view

class CustomerOrder(CreateView):
    model = Order
    slug_field = 'slug'
    slug_url_kwarg = 'slug'
    template_name = 'order.html'
    form_class = CreateOrder
    success_url = reverse_lazy('main:home')

    def form_valid(self, form):
        customer = Customer.objects.get(slug=self.kwargs['slug'])
        menu_ = self.request.POST.get('menu')
        print(customer, "\n")
        print(menu_)
        form.instance.customer_id = customer.pk
        form.instance.user_id = self.request.user.id

        a = super(CustomerOrder, self).form_valid(form)
        b = HttpResponseRedirect(self.get_success_url())
        return a and b

the slug its important because the createview with the customer name so this the urls.py

from django.urls import path
from .views import *

app_name = 'main'

urlpatterns = [
    path('', Home.as_view(), name='home'),
    path('customer/', CreateCustomer.as_view(), name='create-customer'),
    path('<slug:slug>/', CustomerPage.as_view(), name='customer'),
    path('<slug:slug>/order/', CustomerOrder.as_view(), name='customer-order'),
]

if anyone have other methods using function based view i will try and use it thank you very much

One can use the forms cleaned_data attribute to access the cleaned and validated values in the form. These values are normalized to what the field expects. The field used for a ManyToManyField is ModelMultipleChoiceField [Django docs] and it's output normalizes to a queryset of the model instances. Meaning you have a queryset on which you can perform further queries:

from django.db.models import Sum

class CustomerOrder(CreateView):
    model = Order
    slug_field = 'slug'
    slug_url_kwarg = 'slug'
    template_name = 'order.html'
    form_class = CreateOrder
    success_url = reverse_lazy('main:home')

    def form_valid(self, form):
        customer = Customer.objects.get(slug=self.kwargs['slug'])
        menu_queryset = form.cleaned_data['menu']
        total_price = menu_queryset.aggregate(total_price=Sum('price'))['total_price']
        form.instance.customer_id = customer.pk
        form.instance.user_id = self.request.user.id
        form.instance.total_prc = total_price
        # super classes form valid would redirect the user the same way you do, no need to write `return a and b`
        return super().form_valid(form)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM