Untitled

mail@pastecode.io avatar
unknown
plain_text
3 years ago
2.5 kB
24
Indexable
Never
#MODELS.PY

class Invoice_Test_M2M(models.Model):
    id = models.BigAutoField(primary_key=True)
    ref_num = models.CharField(max_length=100)

    def __str__(self):
        return self.ref_num

class Inventory_Test_M2M(models.Model):
    id = models.BigAutoField(primary_key=True)
    inventory_name = models.CharField(blank=True, max_length=100)
    invoice = models.ManyToManyField('Invoice_Test_M2M', through= "Invoice_Inventory_Through")
    price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True)
    
    def __str__(self):
         return self.inventory_name


class Invoice_Inventory_Through(models.Model):
    invoice = models.ForeignKey(Invoice_Test_M2M, on_delete=models.CASCADE)
    inventory = models.ForeignKey(Inventory_Test_M2M, on_delete=models.CASCADE)
    price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True)
    quantity = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True)
    amount = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True)

#FORMS.PY

class Invoice_Inventory_ThroughForm(forms.ModelForm): 

    class Meta:
        model = Invoice_Inventory_Through
        exclude = ()

Inventory_TestLineItem_M2M_Formset = inlineformset_factory(Invoice_Test_M2M, Invoice_Inventory_Through, form=Invoice_Inventory_ThroughForm, fields = '__all__', exclude = [], can_delete = True)#

#VIEWS.PY
class Invoice_M2M_CreateView(CreateView):
    model = Invoice_Test_M2M
    success_url=reverse_lazy('music:album_list')
    garbage = Invoice_Inventory_ThroughForm
    garbage.price_val = 123
    form = garbage

    fields = '__all__'

    def get_context_data(self, **kwargs):
        context = super(Invoice_M2M_CreateView, self).get_context_data(**kwargs)
        if self.request.POST:
            context['track_formset'] = Inventory_TestLineItem_M2M_Formset(self.request.POST)
        else:
            context['track_formset'] = Inventory_TestLineItem_M2M_Formset()
        context['price_val'] = 2
        return context

    def form_valid(self, form):
        context = self.get_context_data(form=form)
        formset = context['track_formset']
        if formset.is_valid():
            response = super().form_valid(form)
            formset.instance = self.object
            formset.save()
            return response
        else:
            return super().form_invalid(form