Sorry the previous message is uncomplete.
Here again,
Models.py:
class BusinessStatus(models.Model):
label = models.CharField('Libellé',max_length=50)
weight = models.IntegerField('Taux', default=10)
final = models.BooleanField(default=False)
def text(self):
return self.label + ' (' + str(self.weight) + '%)'
class Meta:
ordering = ['weight']
verbose_name = 'Etat'
def __str__(self):
"""Cette retourne une chaîne de caractère pour identifier l'instance de la classe d'objet."""
return self.label
class Business(models.Model):
name = models.CharField('Affaire',max_length=200,)
customer = models.ForeignKey(Customer,on_delete=models.CASCADE,verbose_name='Client',
null = True,blank = True)
contact = models.ForeignKey(Contact,on_delete=models.SET_NULL, null=True)
account_exec = models.ForeignKey(Account_exec,on_delete=models.SET_NULL, null=True, verbose_name='Chargé d\'affaires')
amount = models.DecimalField('Montant',max_digits=9, decimal_places=2)
ponderation = models.ForeignKey(BusinessStatus, on_delete=models.RESTRICT)
@property
def amount_pondered(self):
status = BusinessStatus.objects.get(pk=self.ponderation_id)
taux = status.weight
amount = self.amount * taux / 100
return amount
def status(self):
return BusinessStatus.objects.get(pk=self.ponderation_id).text()
def weight(self):
return BusinessStatus.objects.get(pk=self.ponderation_id).weight
def __str__(self):
"""String for representing the Model object (in Admin site etc.)"""
return self.name
def get_absolute_url(self):
return reverse('customer_detail_form', kwarg={'pk':self.pk})
class Meta:
ordering = ['ponderation','amount']
verbose_name = 'Affaire'
The forms which are involved. No way to put amount_pondered in the BusinessForm model related fields. So I have added it with no reference to the model and set it to “disabled”, as you suggested. But I don’t know how to initialize it to the right value, meaning:
For a given business, the field “amount_pondered” which is based on fields on the current instance, amount_poundered = amount * taux / 100, where
taux = BusinessStatus.objects.get(pk=self.ponderation_id).weight
class CustomerForm(ModelForm):
name = forms.CharField(
widget=forms.TextInput(attrs={'autofocus': True}))
class Meta:
model= Customer
fields = '__all__'
widgets = {'creation_date': DatePickerInput}
class BusinessForm(ModelForm):
amount_pondered = forms.CharField(disabled=True)
class Meta:
model = Business
fields = ['name', 'customer', 'account_exec', 'amount','ponderation','contract_type']
#widgets = {'creation_date': DatePickerInput,'signature_date': DatePickerInput,'contract_type': forms.RadioSelect()}
widgets = {'creation_date': DatePickerInput,'signature_date': DatePickerInput}
View which allows to display, update, create and delete businesses for a given customer.
class CustomerUpdateView(UpdateView):
template_name = 'gestcom/customer_update_form.html'
model = Customer
fields = '__all__'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
customer = get_object_or_404(Customer, pk=self.kwargs['pk'])
context['customer_name']=customer.name
context['customer_form'] = CustomerForm(instance = customer)
BusinessFormSet = inlineformset_factory(Customer,Business,can_delete=True,extra=1, form = BusinessForm)
business_formset = BusinessFormSet(instance=customer)
context['business_formset'] = business_formset
return context
def post(self, request, *args, **kwargs):
# récupération de la clé primaire depuis l'url
pk = self.kwargs['pk']
# récupération de l'enregistrement Theme à partir de pk
customer = get_object_or_404(Customer, pk=pk)
# création des forms
customer_form = CustomerForm(instance=customer, data=request.POST)
BusinessFormSet = inlineformset_factory(Customer, Business, can_delete=True, extra=1, form = BusinessForm)
business_formset = BusinessFormSet(instance=customer, data= request.POST)
if 'update' in request.POST:
if customer_form.is_valid():
if business_formset.is_valid():
messages.success(request,'Les données ont été mises à jour')
customer_form.save()
business_formset.save()
contact_formset.save()
address_formset.save()
else:
messages.warning(request, request.POST)
messages.warning(request, 'Données affaires invalides: ' + str(business_formset.errors))
else:
messages.warning(request, request.POST)
messages.warning(request, 'Données de client invalides:' + str(customer_form.errors))
return HttpResponseRedirect(reverse('customer_update_form', args=(customer.id,)))