Reputation: 71
I've five Product objects with 3 product's availability set to True and rest False, I'm trying to set Checkout Status Button to Out of Stock even if one product has availablity set to False.
Because cart view cannot use slug, {% if product.availability %}
is pointless, and can't use 'for loop' or it would create multiple checkout buttons, what's the way to fix this?
Model
class Product(models.Model):
availablity = models.BooleanField()
View
def cart(request):
products = Product.objects.all()
Cart template
{% for product in products %}
<p>{product.name}</p>
<p>{product.price}</p>
{% endfor %}
<!--Checkout Status Button-->
{% if product.availability %}
<a href="#">Checkout</a>
{% else %}
<p>Out of stock</p>
{% endif %}
Upvotes: 0
Views: 53
Reputation: 143187
You should do all calculation in view
and send only single True/False
to template.
For example
products = Product.objects.all()
available = all(x.availability for x in products)
context = {..., "available": available}
{% if available %}
<a href="#">Checkout</a>
{% else %}
<p>Out of stock</p>
{% endif %}
Upvotes: 1
Reputation: 1
In your cart view, you could add a context dictionary to your render()
call?
So basically :
products
for the availability condition and set a variable available
to True/Falserender(cart_template, {'products' : products, 'available' : available})
{% if available %}
Upvotes: 0
Reputation: 933
def cart(request):
products = Product.objects.all()
availibility = True
for prod in products:
if prod.availability = False:
availability = False
break
context = { "products" :products, "availability" :availability }
in Html
if availability` True then show `Checkout` else `Out of Stock`
Upvotes: 0