How to fill a form field based on the value of an autocomplete field in Django template using Ajax+jQuery

落爺英雄遲暮 提交于 2020-01-06 08:05:44

问题


In my application, I am using Ajax+jQuery to populate the unit of measure field based on a product selected by the user using a dropdown. In my products model, each product has been assigned a unit of measure and is picked up to autofill the unit field during order creation.

I am using jQuery to pick up the product from select field and capturing the event using .on('change') event.

Following are the objects:

models.py

Model : Product

class Product(models.Model):
    product_id = models.IntegerField(primary_key=True, default=300000000000000000)
    description = models.CharField(max_length=100, help_text='Prod.Short text')
    default_uom = models.ForeignKey(Unit_of_Measure, null=True, on_delete=models.CASCADE, verbose_name='UoM')

    def __str__(self):
        return '{0} : {1}'.format(self.product_id, self.description)

Model : Unit_of_Measure

class Unit_of_Measure(models.Model):
    uom = models.CharField(max_length=4, unique=True, help_text='Units of measure')
    uom_desc = models.CharField(max_length=50, null=True, help_text='Base UoM description')

    def __str__(self):
        return '{0} ({1})'.format(self.uom, self.uom_desc)

views.py

Function View

def fill_UoM(request):
    product_id = request.GET.get('product_id', None)
    data = {'default_uom': Product.objects.get(product_id=int(product_id)).default_uom.id}
    return JsonResponse(data)

Ajax Function

function fillUoM() 
{
    $.ajax({
            url: '{% url 'fill_unit_of_meas' %}',
            data: {"product_id": matl_sel},       
            dataType: 'json',
            success: function(data) {console.log('The value captured is: ' + data.default_uom)},
            error: function(data) {console.log('Data could not be retrieved')}
        });
};

urls.py: for ajax

urlpatterns = [

    # ...
    path('ajax/uom/', fill_UoM, name='fill_unit_of_meas'),
    # ...

With the above arrangement, I am able to fill the unit of measure field on user selection of product.

However when I am trying to use an autocomplete (DAL) it is failing. The autocomplete view is as shown below:

Autocomplete View

class ProductAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):

        qs = Product.objects.all()
        if self.q:
            qs = qs.filter(description__icontains=self.q)           
        return qs

urls.py: for autocomplete view

urlpatterns = [

    # ...
    path('product_autocomplete/', ProductAutocomplete.as_view(), name='product_autocomplete'),
    # ...

Relevant portion from the form is being shown below:

forms.py

class PurchOrderItem(forms.ModelForm):
    ....
    class Meta:
        model = PurchOrderItem
        fields = ('po_itm_material', 'po_itm_price', 'po_itm_quant_uom', 'po_itm_quantity', 'po_itm_value')
        widgets = {
        ....
        # 'po_itm_material': forms.Select(attrs={'style': 'width:220px'}),     # Without DAL
        'po_itm_material': autocomplete.ModelSelect2(url='product_autocomplete',
                                 attrs={'style': 'width:80px; disabled:True', 
                                 'data-placeholder': 'Click here to select...',
                                 'data-minimum-input-length': 2}),
        ....
        }

My question is:

How do I populate the Unit of Measure field on selection of Product as an Autocomplete (DAL) field (as was being done successfully without autocomplete).

来源:https://stackoverflow.com/questions/59593318/how-to-fill-a-form-field-based-on-the-value-of-an-autocomplete-field-in-django-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!