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 %}
CodePudding user response:
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`
CodePudding user response:
In your cart view, you could add a context dictionary to your render()
call?
So basically :
- Check
products
for the availability condition and set a variableavailable
to True/False - change your render call to
render(cart_template, {'products' : products, 'available' : available})
- change your cart template to use
{% if available %}
CodePudding user response:
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 %}