I would like to apply the autocomplete option for my Preorder.preorder_has_products.through model in order to be able to load products with autocomplete(i tried unsuccessfully).Moreover, I have an inline implementation in order to be able to select for one preorder more than one product. The obstacle is that I have a manytomany field(preorder_has_products) as you can see below and I do not know how to implement the autocomplete.
models.py
class Preorder(models.Model):
client = models.ForeignKey(Client,verbose_name=u'Πελάτης')
preorder_date = models.DateField("Ημ/νία Προπαραγγελίας",null=True, blank=True, default=datetime.date.today)
notes = models.CharField(max_length=100, null=True, blank=True, verbose_name="Σημειώσεις")
preorder_has_products=models.ManyToManyField(Product,blank=True)
def get_absolute_url(self):
return reverse('preorder_edit', kwargs={'pk': self.pk})
class Product(models.Model):
name = models.CharField("Όνομα",max_length=200)
price = models.DecimalField("Τιμή", max_digits=7, decimal_places=2, default=0)
barcode = models.CharField(max_length=16, blank=True, default="")
eopyy = models.CharField("Κωδικός ΕΟΠΥΥ",max_length=10, blank=True, default="")
fpa = models.ForeignKey(FPA, null=True, blank=True, verbose_name=u'Κλίμακα ΦΠΑ')
forms.py
class PreorderHasProductsForm(ModelForm):
product = ModelChoiceField(required=True,queryset=Product.objects.all(),widget=autocomplete.ModelSelect2(url='name-autocomplete'))
class Meta:
model=Preorder.preorder_has_products.through
exclude=('client',)
def __init__(self, *args, **kwargs):
super(PreorderHasProductsForm, self).__init__(*args, **kwargs)
self.fields['product'].label = "Ονομα Προϊόντος"
PreorderProductFormSet = inlineformset_factory(Preorder,Preorder.preorder_has_products.through,form=PreorderHasProductsForm,extra=1)
my views.py for autocomplete
class NameAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
# Don't forget to filter out results depending on the visitor !
if not self.request.user.is_authenticated():
return Product.objects.none()
qs = Product.objects.all()
if self.q:
qs = qs.filter(product__istartswith=self.q)
return qs
my template is written based on this tutorial : https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html
and finally my url for autocomplete:
url(r'^name-autocomplete/$',views.NameAutocomplete.as_view(),name='name-autocomplete'),
My result based on the above snippets is depicted in the attached image.
what could be wrong? I guess one possible issue could be the reference to the manytomanyfield table. Any idea?
