0

I use formset_factory when I get an order for products

product_formset = formset_factory(OrderProductsForm,extra=5)

It works when I use

queryset = Product.objects.all()

in OrderProductsForm(forms.ModelForm):

self.fields['product'] = ModelChoiceField(queryset=Product.objects.all(),empty_label="Ürün Seciniz", widget=forms.Select(attrs={"onChange":'stokKontrol(this.value,this.id)'}))

but it gets all products so page load time increase.

I would like to use queryset=Product.objects.none().

But at that point when I check the form in my view.py

    if request.method == "POST":
        formset = product_formset(request.POST)
        if formset.is_valid():

I get an error

Select a valid choice. That choice is not one of the available choices

Do you have any suggestion ? Thanks

Forms.py

class OrderProductsForm(forms.ModelForm):
    class Meta:
        model = OrderProducts
        fields = ['amount']

    def __init__(self, *args, **kwargs):         
        super(OrderProductsForm, self).__init__(*args, **kwargs)
        self.fields['product_category'] = ModelChoiceField(queryset=ProductCategory.objects.all(),empty_label="Ürün Grubunu seciniz",
                                    widget=forms.Select(attrs={"onChange":'myFunction(this.value,this.id)'}))
        
        #self.fields['product'] = ModelChoiceField(queryset=Product.objects.all(),empty_label="Ürün Seciniz", widget=forms.Select(attrs={"onChange":'stokKontrol(this.value,this.id)'}))
        self.fields['product'] = ModelChoiceField(queryset=Product.objects.none() ,empty_label="Ürün Seciniz",required=False,widget=forms.Select(attrs={"onChange":'stokKontrol(this.value,this.id)'}))
                                    
        self.fields['stok'] = forms.CharField(required=False,disabled=True,max_length=5)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

0

I believe you misunderstand the use of objects.none(). See here for a good explanation.

Product.objects.none() - This simply represents an empty object at first and is used in different use cases. When you set this to the queryset, you will be initialising the queryset to nothing.

The error

Select a valid choice. That choice is not one of the available choices.

is expected since this is not of the available choices for the queryset. To speed the increase of the other method, I would suggest looking at other attributes to speed up the filtering time. This is a possible solution to avoid reloading each time via the use of django-cache.

AzyCrw4282
  • 7,222
  • 5
  • 19
  • 35
  • thanks for your answer @AzyCrw4282 , i create the product list with javascript so ı have to write Product.objects.none() because it cant be blank queryset in the ModelChoiceField as ı know . but i try to use django-cache. – NAZIM AVCI Oct 07 '21 at 22:42