Reputation: 129
Probably an easy one
I am trying to disable (i.e. that the field is present but greyed out) the 'sub_total' field on all formset lines and use javascript to update the field with whatever values are entered into the 'price_estimate' and 'quantity' fields.
I have the following models:
class Requisition(models.Model):
create_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
description = models.CharField(max_length=128, null=True, blank=True,)
total = models.DecimalField(decimal_places=2, max_digits=20, null=True)
class RequisitionLine(models.Model):
requisition = models.ForeignKey(Requisition)
product = models.CharField(max_length=50, blank=False)
quantity = models.PositiveIntegerField()
price_estimate = models.DecimalField(decimal_places=2, max_digits=20)
sub_total = models.DecimalField(decimal_places=2, max_digits=20, null=True)
@property
def get_sub_total(self):
return self.quantity * self.price_estimate
In my view I have
Formset = inlineformset_factory(models.Requisition,
models.RequisitionLine,
form = forms.RequsitionForm,
formset= forms.RequisitionLineForm,
fields=('product', 'price_estimate', 'quantity', 'sub_total'),
extra=2)
In forms
class RequsitionForm(forms.ModelForm):
class Meta:
model = models.Requisition
fields = ['description']
class RequisitionLineForm(forms.BaseInlineFormSet):
sub_total = forms.DecimalField(disabled=True, required=False)
class Meta:
model = models.RequisitionLine
fields = ['product', 'quantity', 'price_estimate', 'sub_total']
In addition to the code above - I have tried to modify the sub_total field on init however, whatever I try it seems that it is ignored.
Any help appreciated
Upvotes: 0
Views: 1024
Reputation: 129
As I suspected - very basic error. The view should look like this (i.e. not setting the formset flag.
Formset = inlineformset_factory(models.Requisition,
models.RequisitionLine,
form = forms.RequisitionLineForm,
fields=('product', 'price_estimate', 'quantity', 'sub_total'),
extra=2)
In addition to this - the form should be modified to use ModelForm (instead of BaseInlineFormSet)
class RequisitionLineForm(forms.ModelForm):
sub_total = forms.DecimalField(disabled=True, required=False)
class Meta:
model = models.RequisitionLine
fields = ['product', 'quantity', 'price_estimate', 'sub_total']
Upvotes: 1