Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save other data after form_valid action in django UpdateView?

Tags:

django

view

model

I have successfully changed a particular field net in my object based on the quantity qty field with the following code.

class OrderDetailsProductEdit(UpdateView):
    model = OrdersPlaced
    fields = ['qty']
    template_name = 'backend/order-details-product-edit.html'
    success_url = '../../../'

    def form_valid(self, form):
        form.instance.net = form.instance.qty * form.instance.price
        # order = Order.objects.get(pk=self.kwargs['order_id'])
        # subtotal = OrdersPlaced.objects.filter(order=order).aggregate(Sum('net'))['net__sum']
        # order.subtotal = subtotal
        # order.save()
        return super(OrderDetailsProductEdit, self).form_valid(form)

However, I am also trying to change the data in ANOTHER model. To be precise, I want the summation of all net values of a query and update the subtotal field in another table.

Please notice the commented out lines under def form_valid. I have no confusion that these lines work, but I need them to execute AFTER the current model is saved, as those are dependent on the value of the current model.

I don't find any errors other than that the subtotal field in ANOTHER model is calculated BEFORE the net field in the current model is saved. Thus, the total is a wrong answer.

What am I doing wrong?

like image 222
MiniGunnR Avatar asked Jan 24 '16 10:01

MiniGunnR


1 Answers

Simply move the instruction after calling super

    def form_valid(self, form):
        form.instance.net = form.instance.qty * form.instance.price
        redirect_url = super(OrderDetailsProductEdit, self).form_valid(form)
        order = Order.objects.get(pk=self.kwargs['order_id'])
        subtotal = OrdersPlaced.objects.filter(order=order).aggregate(Sum('net'))['net__sum']
        order.subtotal = subtotal
        order.save()
        return redirect_url

or just do what calling super does (save model and redirect to success_url) by yourself

    def form_valid(self, form):
        form.instance.net = form.instance.qty * form.instance.price
        self.object = form.save()
        order = Order.objects.get(pk=self.kwargs['order_id'])
        subtotal = OrdersPlaced.objects.filter(order=order).aggregate(Sum('net'))['net__sum']
        order.subtotal = subtotal
        order.save()
        return HttpResponseRedirect(self.get_success_url())
like image 85
smesh Avatar answered Nov 11 '22 00:11

smesh