How i can send recently save data into template in same view function in django

Viewed 822

view.py
In the below code, I'm saved my recent data in model and create a dictionary order = order.save() because I can use this in my template. When I run the code the order is having ```None`` value.

What i can do for it.

     def post(self, request, product_id):
          product = Product.objects.get(id=product_id)
          if request.POST['address'] and request.POST['quantity']:
               order = Order()
               order.or_proName = product.pro_name
               order.or_companyName = product.companyName
               order.or_quatity = request.POST['quantity']
               order.or_quatity = int( order.or_quatity)
               orderPrice = order.or_quatity*product.Sale_Price
               order.or_bill = 100 + orderPrice
               order.pub_date = timezone.datetime.now()
               product.Quantity -= order.or_quatity
               product.save()
               order = order.save()
               args = {'order':order}
               return render(request, self.red_templateName, args)


2 Answers

You should not assign the result of the .save() function to order, since that is indeed None. Just .save() the order, and use the order function further in your view:

def post(self, request, product_id):
    product = Product.objects.get(id=product_id)
    if request.POST['address'] and request.POST['quantity']:
        order = Order()
        order.or_proName = product.pro_name
        order.or_companyName = product.companyName
        order.or_quatity = request.POST['quantity']
        order.or_quatity = int( order.or_quatity)
        orderPrice = order.or_quatity*product.Sale_Price
        order.or_bill = 100 + orderPrice
        order.pub_date = timezone.datetime.now()
        product.Quantity -= order.or_quatity
        product.save()
        order.save()
        args = {'order':order}
        return render(request, self.red_templateName, args)

You should however define an else case as well, since the post method is supposed to always return a HttpResponse object, for example an error mesage.

Related