[Fixed]-Loop in django views by "str" method

1👍

Try the following, which calls the People.__str__() for each entry in your people_list.

def index(request):
    people_list = People.objects.all()
    output = ', '.join([str(p) for p in people_list])
    return HttpResponse(output)

You have an error in your original snippet when you’re attempting to join the list of people as a string:

output = ', '.join([People for p in people_list])

You’re generating a list of uninstantiated classes (not the resulting instances or objects of those classes), replacing your list of people.

Leave a comment