I am building my first Django application, a 'simple' web-based withdrawal and deposit system. A user's items are stored in an "Items" class:
(models.py)
class Item(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
stock = models.IntegerField()
def __str__(self):
return self.title
Each "Cart" item is stored as an "OrderItem":
(models.py)
class OrderItem(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.IntegerField(default=0)
def __str__(self):
return self.item.title
To add items to their cart, users will go to a page that displays all of their items in forms, which they can fill and click the "Add to cart button" to create that OrderItem.
(forms.py)
class OrderItemForm(ModelForm):
class Meta:
model = OrderItem
fields = ["quantity", "item"]
The problem that I am having with this approach is that I need many OrderItem forms, with their "item" variable prefilled OR somehow instantiating said value. In other words, I don't want the approach Django provides by default with a dropdown, i need each of those dropdown items rendered as separate forms.
(storage.html)
<div class="row">
<div class="col-md-9">
<div class="row">
{% for i in items %}
<div class="card">
<img src="static 'demo/logo.png" class="card-img-top">
<h5 class="card-title ml-2">{{i}}</h5>
<form class="form-inline" method="POST"> {% csrf_token %}
<div class="form-group ml-2 mb-2">
{{form.quantity}}
<input type="submit" class="btn" value="Add to Cart">
</div>
</form>
</div>
{% endfor %}
</div>
</div>
As you can see, my solution to this problem has been creating a for loop inside my html template that displays these forms, but I am at a loss in which way I can pass the "i" instance to the "form.item" in this way. All the info I've found online assigns some form variable a default value, but that wouldn't work with what I'm trying to accomplish... Maybe tackling this from the html level is not a good solution but I am quite lost at this point.
Thanks!