1

I'm using javascript (plus AngularJS and Restangular) to call a Django endpoint and retrieve an array of proposals. But I can't seem to get my Django syntax right.

How do I return and array of objects in a given Django model?

def proposal_api(request):
    response = {}
    response['proposal_list'] = Proposal.objects.all()
    return response

The Django View above throws the following Attribute error: 'dict' object has no attribute 'status_code'

Once I receive the array of proposals from the above Django View (with IDs, names, questions, etc...) I'll use AngularJS to display everything.

Michael Romrell
  • 1,026
  • 5
  • 15
  • 31

1 Answers1

7

You need to read up on writing views in the documentation. A view function should return an HTTP response object.

The simplest way would be to just use the HttpResponse object from Django like so

from django.core import serializers
from django.http import HttpResponse

def proposal_api(request):
    response = {}
    response['proposal_list'] = serializers.serialize("json", Proposal.objects.all())
    return HttpResponse(response, content_type="application/json")

If you are building an API, however, I would strongly encourage you to checkout TastyPie or Django-Rest-Framework.

patsweet
  • 1,548
  • 10
  • 12
  • 1
    A vote for Django Rest Framework, it's going to give you a lot of tools that help in developing an API that angular can consume with ease. – stormlifter Mar 18 '14 at 20:48
  • Should also include that should set `response['success'] = True` if using with Ajax. – Ford Mar 18 '14 at 20:50
  • That Worked perfectly. Thank you! I should have know I was going to need to serialize the response. – Michael Romrell Mar 18 '14 at 21:13