Django-select2 is not showing model data

580 Views Asked by At

I have configured django-select2 but data from models is not showing in field. I had tried many methods like normal forms as well as modelform.

I have also tried initialise the field as query, still its not working accordingly. Same code:

forms.py

class PricekeyForm(forms.ModelForm):
    uom = forms.ModelChoiceField(
            queryset=UnitOfMeasurement.objects.all(),
            widget=ModelSelect2Widget(
                model=UnitOfMeasurement,
                search_fields=['unit__icontains']
            )
        )

    class Meta:
        model = Pricekey
        fields = ['uom', 'sales_price', 'return_price', 'damage_return_price',]

    def __init__(self, *args, **kwargs):
        self.fields['uom'].widget.queryset

models.py

class Pricekey(BaseModel):
    itemcode = models.CharField(max_length=255,null=True,blank=True)
    uom = models.ForeignKey('UnitOfMeasurement',on_delete=models.CASCADE,null=True,blank=True) 
    sales_price = models.FloatField(null=True,blank=True)
    return_price = models.FloatField(null=True,blank=True)
    damage_return_price = models.FloatField(null=True,blank=True)
    expiry_return_price = models.FloatField(null=True,blank=True)

What i wanted is, select2 filled with data from the db. Please tell me where i went wrong. I checked the documentation also for django-select2. please help me.

1

There are 1 best solutions below

0
On

I'll just give my suggestions as your code is not very ellaborate.

  1. I hope you have a field unit in your UnitOfMeasurement Model.

  2. I'd think your problem lies in the __init__ method. Removing the line self.fields['uom'].widget.queryset should probably work for you as I don't see any reason for it to be there.