Django: populate the field based on previous field value - missing the last step to make it work

28 views
Skip to first unread message

Sylvain Martel

unread,
Oct 15, 2017, 10:06:06 AM10/15/17
to Django users

Hi, I asked this over Stackoverflow during the summer, but strangely, no replies.  Bad timing to post in the summer I guess. I'll include the link as code formating is cleaner there : https://stackoverflow.com/questions/45225998/django-populate-the-field-based-on-previous-field-value-missing-the-last-step

Like many, I want to populate a field in a django form based on what is selected in another field. I've read alot of answers with javascript(I struggle in javscript, so that's where I'm having trouble with the exemples), and I almost got it working, but the last step(updating the field itself) isn't working so I'd love some help with that part.


Here are the 2 fields. The first fieldthat gets populated from a query and is located in a div named #merch in the form

 merch_price = forms.DecimalField(label='Price', min_value=0, max_value=800, initial='0.00',decimal_places = 2, max_digits=10)
merchandise = forms.ModelChoiceField(label='Merchandise', queryset=Merchandise.objects.all(),


Upon selection, the second field(div named #price) should then display the price based on the merchandise selected. I created the view for the ajax request:

def check_item_price(request):
if request.method == "GET":
    item = request.GET.get('item', '0')#the zero as default doesn't seem to work. To verify
    price = Merchandise.objects.get(id = item)      
return JsonResponse(price.item_price, safe=False)#is it safe to turn safe off?

and the url


 url(r'^_item_price', views.check_item_price, name='_item_price' )

Calling the url manually works great, it returns the price in json format

And here is the javascript that is in the html form. The first part works, upon change it calls the url and a json object is returned, but the second part that should update the second field isn't working. I admit my lack of knowledge in javascript is probably at fault here. I tried many variations based on examples, none worked for me.

 <script type="text/javascript"> jQuery(document).ready(function() { $('#merch').change(function() { var item = $(this).find(':selected').val(); $.getJSON('/classes/_item_price/',{item:item}, function(data) { $('#price').append("<option value=" + data.value + "></option>"); }); }); }); </script>

Any pointers on what to fix in the javascript? Thanks!

Reply all
Reply to author
Forward
0 new messages