i'm trying to create a list of items that belong to a specific contract of a user in django. In this list, the user must be able to acces a form with all the items that belong to this specific contract, and edit their value.
I've tried to use formsets, but the Items are not related to the contract, despite of a M2M field in the contract itself, so the error that i've been facing is:
'contract_generator.Item' has no ForeignKey to 'contract_generator.ClientContract'.
The are the models that are in use:
class ClientContract(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
original_contract = models.ForeignKey(Contract, on_delete=models.CASCADE, null=True, blank=True)
contract_name = models.CharField(max_length=60)
address = models.TextField(blank=True, null=True)
# Value related information
total_value = models.DecimalField(blank=True, null=True, max_digits=12, decimal_places=2)
installments = models.IntegerField(null=True, blank=True)
# Items and clausules of the contract
items = models.ManyToManyField(Item, blank=True, null=True)
clausules = models.ManyToManyField(Clausule, blank=True, null=True)
def __str__(self):
return self.contract_name
class Item(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
item_name = models.CharField(max_length=90)
item_type = models.CharField(max_length=90)
item_value = models.FloatField(blank=True, null=True, max_length=12)
item_qt = models.FloatField(blank=True, null=True, max_length=12)
item_total = models.FloatField(blank=True, null=True, max_length=12)
# Unity options
METERS = 'MT'
LITERS = 'LT'
UNITY_CHOICES = [
(METERS, 'Meters'),
(LITERS, 'Liters'),
]
unity = models.CharField(choices=UNITY_CHOICES, default=METERS, max_length=20)
def __str__(self):
return self.item_name
This is the view that i've built using formset:
@login_required
def adjust_values(request, id):
ItemFormSet = inlineformset_factory(ClientContract, Item, fields=('item_value', 'item_qt', 'item_total'))
contract = get_object_or_404(ClientContract.objects.filter(user=request.user), pk=id)
formset = ItemFormSet(instance=contract)
if request.method == 'POST':
formset.ItemForm(request.POST)
if formset.is_valid():
formset.save()
return redirect('/')
context = {'formset': formset}
return render(request, 'item_formset.html', context)
Is it possible to maybe create a loop to iterate between the forms, of the items that are linked in this specific contract?