looking for some solutions? You are welcome.

SOLVED: How to filter queryset in django inline form?

Niladry Kar:

I want to filter certain modelfield in my inlineform to specific user and company.

But was unable to do in django inline formset.

This are my models:

class Purchase(models.Model):    
    user            = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)    
    company         = models.ForeignKey(Company,on_delete=models.CASCADE,null=True,blank=True)    
    party_ac        = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='partyledger')   
    purchase        = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='purchaseledger')    
    total           = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True)       purchases

class Stock_total(models.Model):
    purchases   = models.ForeignKey(Purchase,on_delete=models.CASCADE,null=True,blank=False,related_name='purchasetotal') 
    stockitem   = models.ForeignKey(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='purchasestock') 
    quantity_p  = models.PositiveIntegerField()
    rate_p      = models.DecimalField(max_digits=10,decimal_places=2)
    grand_total = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True)

My views:

class Purchase_createview(ProductExistsRequiredMixin,LoginRequiredMixin,CreateView):
    form_class  = Purchase_form
    template_name = 'stockkeeping/purchase/purchase_form.html'    

    def get_context_data(self, **kwargs):
        context = super(Purchase_createview, self).get_context_data(**kwargs) 
        context['profile_details'] = Profile.objects.all()
        company_details = get_object_or_404(Company, pk=self.kwargs['pk'])
        context['company_details'] = company_details
        if self.request.POST:
            context['stocks'] = Purchase_formSet(self.request.POST)
        else:
            context['stocks'] = Purchase_formSet() 
        return context

    def form_valid(self, form):
        form.instance.user = self.request.user
        c = Company.objects.get(pk=self.kwargs['pk'])
        form.instance.company = c
        form.instance.counter = counter
        context = self.get_context_data()
        stocks = context['stocks']
        with transaction.atomic():
            self.object = form.save()
            if stocks.is_valid():
                stocks.instance = self.object
                stocks.save()
        return super(Purchase_createview, self).form_valid(form)

In my forms I have tried this:

class Stock_Totalform(forms.ModelForm):

    class Meta:
        model  = Stock_Total
        fields = ('stockitem', 'Quantity_p', 'rate_p', 'Disc_p', 'Total_p')

    def __init__(self, *args, **kwargs):
        self.User = kwargs.pop('purchases.User', None)      
        self.Company = kwargs.pop('purchases.Company', None)
        super(Stock_Totalform, self).__init__(*args, **kwargs)
        self.fields['stockitem'].queryset = Stockdata.objects.filter(User = self.User, Company= self.Company)
        self.fields['stockitem'].widget.attrs = {'class': 'form-control select2',}
        self.fields['Quantity_p'].widget.attrs = {'class': 'form-control',}
        self.fields['rate_p'].widget.attrs     = {'class': 'form-control',}
        self.fields['Total_p'].widget.attrs = {'class': 'form-control',}

Purchase_formSet = inlineformset_factory(Purchase, Stock_Total,
                                            form=Stock_Totalform, extra=6)

But the filtering of queryset is not showing any item if it is present under specific User and also under specific company.

Can anyone help me with the exact query that will filter objects under specific user and company.

Thank you



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

No comments:

Recent