how to get cart total amount in Django? - python

I have deals products and normal products. I have a function for normal products which calculate grand toal is working fine but when I add deal product in the cart it did calculate the grand total but only normal prices not deals prices
get total of one product with quantity
def get_total(self):
price = self.product.price
quantity = self.quantity
total = price*quantity
print(total)
return total
function of get cart total
#property
def get_cart_total(self):
orderitem = self.orderitem_set.all()
total = sum(item.get_total for item in orderitem)
return total
i have two fields in databse
price and deal_price
how i can calculate complete correct cart total?

You need to compute the grand total using deal_price.
Example
I'm not sure if this would work since i haven't seen the complete source but you need something like this
def get_deal_total(self):
price = self.product.deal_price
quantity = self.quantity
total = price*quantity
print(total)
return total
#property
def get_cart_deal_total(self):
orderitem = self.orderitem_set.all()
total = sum(item.get_deal_total for item in orderitem)
return total

Related

Why am I getting an incorrect payment total via Stripe in Python?

I'm trying to make a payment through the ecommerce website I created. The payment successfully went through but the total amount charged is different than what I wanted to charge. For example, I want to charge $29.19 but I get charged $2,918.90. I know it has something to do with the decimal places, but I seem to have it correct; 2 decimal places.
I tried adding decimal to the subtotal, tax, and shipping to get a decimal total, though it came, I still had a wrong total amount.
My cart.py:
def get_total(self):
subtotal = sum(Decimal(item['price']) * int(item['quantity']) for item in self.cart.values())
tax = Decimal('0.10')
tax_price = sum(Decimal(item['price']) * int(item['quantity']) for item in self.cart.values()) * Decimal(tax)
shipping_cost = 5
total = Decimal(subtotal) + Decimal(tax_price) + Decimal(shipping_cost)
return total
My Payment views.py:
#login_required
def CartView(request):
cart = Cart(request)
total = str(cart.get_total())
total = total.replace('.', '')
stripe.api_key = ''
intent = stripe.PaymentIntent.create(
amount=total,
currency='usd',
metadata={'userid': request.user.id}
)
Order class:
total_paid = models.DecimalField(max_digits=5, decimal_places=2)
OrderItem class:
price = models.DecimalField(max_digits=5, decimal_places=2)
If you look at the PaymentIntent object in the Stripe documentation you can see that the amount parameter accepts the price in the smallest currency unit.
Amount intended to be collected by this PaymentIntent. A positive
integer representing how much to charge in the smallest currency unit
(e.g., 100 cents to charge $1.00 or 100 to charge ¥100, a zero-decimal
currency).
If you want to charge $1.00 the amount you pass to the PaymentIntent should be 100. If you want to charge $29.19 the amount you pass should be 2919.
Instead of total = total.replace('.', '') try making a int amount and multiply it by a 100 (or store the prices in the cents beforehand).

inventory question regarding adding and removing product using dictionary

I am working on task like this, in a company, they want to sale product called 'computer'.
if enough stock does not exists before the sale date, it should give message for insufficient qty , message.
Also should give information of total available product quantity for sale before that date, and it's valuation.
if company have enough quantity for sale, than it should display message of remaining qty of that product and it's valuation.
e.g.
valuation = quantity * purchase price
my code
import datetime
class Supplier:
def add_supplier(self, name, address, email, contact_no):
"""
Function: Used to add supplier details.
Parameter:name: Supplier Name
address: Supplier address
email: Supplier email
contact_no: Supplier Contact detail
Return: Nothing
"""
self.name = name
self.address = address
self.email = email
self.contact_no = contact_no
class Product:
def add_product(self, name):
"""
Function: To add product in to an inventory.
Parameter: Product name
Return: Nothing
"""
self.name = name
class Company(Supplier, Product):
data_dict = []
def purchase(self, product_obj, qty, price, date=datetime.date.today()):
"""
Function: Used to purchase product.
Parameter: product_obj: Product object.
qty: Product quantity.
price: Product price.
date: Product date.
Return: Nothing
"""
self.data_dict.append({'product': product_obj.name, 'qty': qty, 'price': price, 'date': str(date)})
def sale(self, sale_qty, sale_date):
"""
Function: To sale product from warehouse.
Parameter: sale_qty: Product sell quantity.
sale_date: Product sell date.
Return: Nothing
"""
self.newdict = (sorted(self.data_dict, key=lambda x: x['date']))
assert sale_qty > 0
unit_val = 0
rqilr = 0
rpilr = 0
qty = 0
price = 0
sum_qty = 0
sum_price = 0
#print(newdict) # testing.
for i, row in enumerate(self.newdict):
if row['date'] > sale_date:
print("Sorry, not enough quantity.\nStart the purchase order procedure pls!\n")
qty += row['qty']
price += row['price']
unit_val = price/qty
# we have enough Computers in stock.
if qty >= sale_qty:
break
else: # loop completes normally
for i in self.newdict:
sum_price += i['price']
sum_qty += i['qty']
print("Sorry, not enough qty. Operation cancelled.\nCurrent quantity = {} and valuation = {}".format(sum_qty, sum_price))
# remaining_qty_in_last_row sort name = rqilr
rqilr = qty - sale_qty
rpilr = rqilr * unit_val
self.newdict = [{**row, 'price': rpilr, 'qty': rqilr}] + self.newdict[i + 1:]
#print(self.newdict)
# For current quantity and valuation
for i in self.newdict:
sum_price += i['price']
sum_qty += i['qty']
print("Sold!\n available quantity = {} and valuation = {}".format(sum_qty, sum_price))
C = Company()
PRODUCT_OBJ = Product()
PRODUCT_OBJ.add_product('Computer')
while True:
option = int(input("""1. You want to add stock of the product!"
2. Want to sale product?
"""))
if option == 1:
qty = int(input("Enter the qty of the product.\n"))
price = float(input("Enter the price of the product.\n"))
purchase_date = input("Enter purchase date.\n")
C.purchase(PRODUCT_OBJ, qty, price, purchase_date)
elif option == 2:
qty = int(input("Enter the qty you wanna sale, pal!"))
sale_date = input("Enter sale date.\n")
C.sale(qty, sale_date)
else:
print("Enter only 1 & 2 option.\n")
after executing program I am having menu like in program.
You want to add stock of the product!
Want to sale product?
but output not getting proper output of remaining quantity and valuation.
Any suggestion , how to make it right?

Get the values from one app to another in Django

I am working on creating shopping cart. I am still in learning phase. I need to know how I can pass/use values from shop's models.py to cart's cart.py.
shop/models.py
class Product(models.Model):
delivery_price = models.DecimalField(max_digits=10, decimal_places=0,default=0)
support_price = models.DecimalField(max_digits=10, decimal_places=0,default=0)
cart/cart.py : I think this is the file where I need to get delivery_price and support_price. I dont know how I can get these two values. I want to add these prices and multiply it by quantity (something like Product.delivery_price + Product.support_price * item.quantity -> not sure about the way this is being done) How is this flow working? If anyone help me understand, it would be great.
class Cart(object):
def __init__(self, request):
def add(self, product, quantity=1,update_quantity=False, support_req=False):
"""
Add a product to the cart or update its quantity.
"""
product_id = str(product.id)
if product_id not in self.cart:
self.cart[product_id] = {'quantity': 0,
'price': str(product.price)}
if update_quantity:
self.cart[product_id]['quantity'] = quantity
else:
self.cart[product_id]['quantity'] += quantity
self.save()
def __iter__(self):
"""
Iterate over the items in the cart and get the products
from the database.
"""
product_ids = self.cart.keys()
# get the product objects and add them to the cart
products = Product.objects.filter(id__in=product_ids)
for product in products:
self.cart[str(product.id)]['product'] = product
for item in self.cart.values():
item['price'] = Decimal(item['price'])
item['total_price'] = item['price'] * item['quantity']
yield item
def __len__(self):
"""
Count all items in the cart.
"""
return sum(item['quantity'] for item in self.cart.values())
def get_total_price(self):
return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())
I used code from https://github.com/twtrubiks/django-shop-tutorial
First you need to create an instance of your Product model. This is done by instantiate it like any other Python class (see documentation)
product = Product(100,10) #this is an example
Then you can add a product to a cart by using the built-in add method:
cart.add(product)
Note
You'll also need to instantiate a cart the same way as you did for your product.Then, you'll have access to other methods decalred in the Cart which handles calculating the total price.
And just for your understanding, you were asking how to Get the values from one app to another in Django. Well, in this case, since your passing a product object to cart via product parameter, you have acess to its attributes.

How to store values using onchange in odoo?

If I save the amount_total value changes to prior position because it is readonly. i want that field to be readonly.
discount = fields.Selection([('fixed', 'fixed Price'), ('percentage', 'Percentage')], string="Discount")
amount = fields.Float("Amount")
total = fields.Float("Discounted Amount", store=True, compute='discount_amount')
amount_total = fields.Monetary(string='Total', store=True,readonly=True, compute='_amount_all')
#api.onchange('total')
def totalamount(self):
if self.total:
self.amount_total -= self.total
How to deal with this
Instead of writing on change function you can do like the following
#api.depends('total')
def _amount_all(self):
if self.total:
total_amount = self.amount_total - self.total
self.update({
'amount_total': total_amount
})

Python: adding multiple products and prices to a shopping cart

I am completing the Python course on CodeAcademy (I am running the code on my computer not CodeAcademy) and wrote this piece of code to add items to a shopping cart. The shopping cart is a dictionary.
class ShoppingCart(object):
"""Creates shopping cart objects
for users of our fine website."""
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name
def add_item(self, product, price):
"""Add product to the cart."""
if not product in self.items_in_cart:
self.items_in_cart[product] = price
print product + " added."
else:
print product + " is already in the cart."
my_cart = ShoppingCart("Amy")
my_cart.add_item("Nishiki Modulus", "$400")
print my_cart.items_in_cart
This code works and returns:
Nishiki Modulus added.
{'Nishiki Modulus': '$400'}
But I would like to figure out how to add several items (and prices) at the same time. I have been experimenting with no luck.
I ran
class ShoppingCart(object):
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name
def add_item(self, product, price):
"""Add product to the cart."""
for products in product:
if not products in self.items_in_cart:
self.items_in_cart[products] = price
print "added."
else:
print "Product is already in the cart."
my_cart = ShoppingCart("Amy")
my_cart.add_item(["Nishiki Modulus", "Trek 700", "Fuji Sportif"], ["$400", "$450", "$700"])
print my_cart.items_in_cart
As I predicted, the keys are right but not the values. This returns:
added.
added.
added.
{'Trek 700': ['$400', '$450', '$700'], 'Fuji Sportif': ['$400', '$450', '$700'], 'Nishiki Modulus': ['$400', '$450', '$700']}
I'm think something along the lines of:
for products, price in product.items():
but then I can't figure out how to correctly add the list to items_in_cart
Can anyone point me in the right direction? Please let me know if anything is unclear.
You can zip the products and their prices like this
for prod, money in zip(product, price):
if not prod in self.items_in_cart:
self.items_in_cart[prod] = money
print "added."
else:
print "Product is already in the cart."
This will zip the product and price list and give one value at a time from both the lists. So we will get the product and its corresponding price.
Or you can iterate the product list, and get the corresponding value from the price with the index, like this
for index, prod in enumerate(product):
if not prod in self.items_in_cart:
self.items_in_cart[prod] = price[index]
print "added."
else:
print "Product is already in the cart."
You can try with simple-indexed for loop:
def add_item(self, product, price):
"""Add product to the cart."""
for index in range(len(product):
if not product[index] in self.items_in_cart:
self.items_in_cart[product[index]] = price[index]
print "added."
else:
print "Product is already in the cart."
Or use zip:
for products, prices in zip(product, price):
You are setting the value of items_in_cart[product] to price, a list of strings. You should be setting it to one of the strings in price.
Here's the ShoppingCart class fixed:
class ShoppingCart(object):
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name
def add_item(self, product, price):
"""Add product to the cart."""
priceIndex = 0
for products in product:
if not products in self.items_in_cart:
self.items_in_cart[products] = price[priceIndex]
print "added."
else:
print "Product is already in the cart."
priceIndex += 1
I would add a new method add_items that calls your original add_item in a loop. This will keep your code cleaner and easier to work with.
class ShoppingCart(object):
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name
def add_item(self, product, price):
"""Add product to the cart."""
if not product in self.items_in_cart:
self.items_in_cart[product] = price
print product + " added."
else:
print product + " is already in the cart."
def add_items(self, products, prices):
for product, price in zip(products, prices):
self.add_item(product, price)
my_cart = ShoppingCart("Amy")
my_cart.add_items(["Nishiki Modulus", "Trek 700", "Fuji Sportif"], ["$400", "$450", "$700"])
print my_cart.items_in_cart

Categories

Resources