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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
Should also include that should set response['success'] = True if using with Ajax.
That Worked perfectly. Thank you! I should have know I was going to need to serialize the response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.