1

what I am trying to do is send a $http GET request to a django url pattern and return a .json file. Can I use urlpatterns to return a file instead of a view?

is this even possible?

currently form/data is returning 500

testModule.js

angular.module('mod1', ['mod2'])

.controller('resorcesCtrl', ['mod2Factory',
     function(mod2Factory) {
        mod2Factory.getJSON();
     }
]);


angular.module('mod2', [])
   .factory('mod2Factory', [ '$http',
      function($http) {

        var getJSON = function() {
           return $http({
           url: "/form/data",
           method: "GET"
        })
      }

      return {
         getJSON:getJSON
      }; 
    }
  ])

urls.py

url(r'^form/data', 'myApp.views.getJSON', name='getJSON'),

views.py

def getJSON(request):
    context = {
        "json": json
    }
    return render(request, '', context)
1
  • What is the content of your 500 error? Can you put it here with the stacktrace? Which version of Django? Commented Mar 24, 2015 at 23:17

2 Answers 2

2

Starting with Django 1.7, there is a new response object called JsonResponse.

Your view can be as simple as:

from django.http import JsonResponse

def getJSON(request):
    # context is a Python dict.
    context = {
        "key": "value",
        "other_key": 365,
    }
    return JsonResponse(context)

The context must be a valid JSON serializable object. See the docs for more detail about JsonResponse. If you have any trouble with serialization, you can pass your own encoder to JsonResponse to handle custom data types, read more.

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

Comments

1

I prefer use a function like that

import json
from django.http import HttpResponse

def json_responder(**kwargs):
    return HttpResponse(json.dumps(kwargs), content_type="application/json")

def yourview(request):
    return json_responder(type='error', msg='a message")

and that can be used on every django version

Comments

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.