I am having a little bit of trouble with my django project. Let's say, for example, I have a view written up to pull data from the database and return an array of names for a phonebook. When I put the returned data (phonebook contacts array) into an alert, the names come up fine, ex: "Adam", "Brittany", etc. When I console.log the returned data, the item names also are returned ("Adam", "Brittany", etc.). Using javascript, I am trying to get the data to display inside of a td cell, just the individual item names, so that there is a div for Adam, a div for Brittany, etc. Unfortunately, instead of displaying the contact names, my code is displaying [Object object] multiple times. How do I get the contact name to take place of [Object object]? Why is [Object object] appearing instead? Thank you for any help you can provide.
My code is as follows:
/models.py:
class phonebook(models.Model):
name = models.Charfield(max_length=200)
phone_number = models.CharField(max_length=100)
/views.py:
def phonebook_home(request):
global phonebook
phonebook = phonebook.objects.order_by('name')
try:
indexStart = int(request.GET.get('indexStart'))
indexEnd = indexStart + 3
next_three_contacts = phonebook.objects.order_by('name')[indexStart:indexEnd]
serializer = contactSerializer()
data = serializer.serialize(next_three_contacts)
contact_count = phonebook.objects.count()
moreAvailable = ''
if indexEnd + 3 <= contact_count:
moreAvailable = 'more_than_two'
elif indexEnd + 2 <= contact_count:
moreAvailable = 'two_more'
else:
moreAvailable = 'no_more'
return JsonResponse({'returned_contacts': data, 'moreAvailable': moreAvailable})
except:
pass
/Serializers.py:
from django.core.serializers.python import Serializer
class contactSerializer(Serializer):
def end_object(self, obj):
self._current['id'] = obj._get_pk_val()
self.objects.append( self._current )
/main.js:
function generateCard(contactNameC, iconC) {
var card = "<td class='tablecells'><a class='tabletext' href='#'><span class='fa "
+ iconC + " concepticons'></span><h2 class='header'>" + contactNameC
+ "</h2><p><span class='fa fa-chevron-circle-right'></span></p></a></td>";
return card;
}
var indexLast = 9;
$(".showmorebutton").click(function() {
var config = {
type: 'GET',
url: SUBMIT_URL,
data: {
indexStart: indexLast
},
dataType: 'json',
success: function (data, textStatus_ignored, jqXHR_ignored) {
var moreAvailable = data.moreAvailable;
var contacts = data.returned_contacts;
var contactNameLoop = $.each(contacts, function(idx, obj) {
console.log(obj.name);
alert(obj.name)
});
if (moreAvailable === "more_than_two") {
$("table").append("<tr></tr>");
for (var i = 0; i < 3; i++) {
var contactName = contactNameLoop[i]
var icon = "fa facogs";
$("table tr:last").append(generateCard(contactName, icon));
}
}
}
};
$.ajax(config);
indexLast += 3;
});
edit:
I also made sure to import the proper modules/files into each python file.
objto the console and see what the structure is.