Boris The Animal Boris The Animal - 5 months ago 60
Javascript Question

How to get description of object from python django backend to AJAX in front end?

In models I have specified object description

def __unicode__(self): ...............................

And I want to see this description in my dynamic drop boxes generated with Ajax.
But I just get [object Object] in dropdown.

My data flows in following way:

1-I have sterilizer in my api

class LeaseTermSerializer(serializers.ModelSerializer):
class Meta:
fields = '__all__'

2-I have api method in view

@api_view(['GET']) @csrf_exempt def get_leaseterm(request, tid):
leasetermobj = LeaseTerm.objects.filter(lease=tid,is_active = True)
leaseterm_serializer = LeaseTermSerializer(leasetermobj, many=True)
response = Response(
return Response(,status=status.HTTP_200_OK)

3-In my template I build it like this

function getleaseterm() {

//get a reference to the select element
$select = $('#leaseterm');
//request the JSON data and parse into the select element
var l_id = ($("select[name='lease'] option:selected").attr('value'));
l_url = "/api/get_leaseterm/"+l_id+"/";

url: l_url,
//clear the current content of the select
$select.append('<option value="-1">Select term </option>');
//iterate over the data and append a select option

$.each(data1, function(key, val){
$select.append('<option value="' + + '">' + val + '</option>');



Problem is that the "val" value I display in dropdown if I I don't specify what field I want to show will display [object Object] for all the values in dropdown when I want it to display description of object I have specified for my model.

How can I see my object description in my dropdown?

Answer Source

in your case val is the json object by your serializer declare) so as result you see [object Object], you are confusing with django template where you can use such way. but you can, add charfield to your serializer, and use it

as_char = serializers.CharField(source='__unicode__')

in html:

$select.append('<option value="' + + '">' + val.as_char + '</option>');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download