Reputation: 138
A product has many items. I can display items of a particular product neatly in a table. But when I try to save, on postback only the last element in the table is saved for all the items of that product. This might be because I am only returning last element back from my html. Can anyone please tell me any elegant way to do this? Here is my code.
models.py
class Item(models.Model):
Product = models.ForeignKey("Product", related_name = "Attributes")
Name = models.CharField(max_length=1000, blank=True, null=True)
Type = models.CharField(max_length=1000, blank=True, null=True)
forms.py
class ItemForm(ModelForm):
class Meta:
model = Item
fields = ['Name', 'Tag']
views.py
def getItems(request, product_id):
items = get_list_or_404(Item, Product = product_id)
itemslist = []
if request.method == 'GET':
for item in items:
itemform = ItemForm(instance=item)
itemlist.append(itemform)
else:
for item in items:
itemform = ItemForm(request.POST, instance=item)
itemlist.append(itemform)
for tempform in itemlist:
if tempform.is_valid():
tempform.save()
return render(request, 'knowledgebase.html', {'product_id': product_id, 'itemslist': itemslist})
html file:
<tbody>
{% for itemform in itemslist%}
<tr>
<td class="td"> {{ itemform.Name }} </td>
<td> {{ itemform.Tag }} </td>
</tr>
{% endfor %}
</tbody>
Upvotes: 1
Views: 202
Reputation: 116
The only last form is saving because you are sending the template a list of individual forms to render. Without seeing the rest of your html I'd say you only have one submit button. Since the other forms are not being fed data on submit they are not considered bound and thus will not return True when is_valid() is called and will not reach tempform.save() https://docs.djangoproject.com/en/1.9/ref/forms/api/#bound-and-unbound-forms
Try printing out the value of each tempform.is_bound() to test this.
A way to mitigate this is to use formsets or create your own custom form with multiple fields for each model instance.
Upvotes: 1