imkost
imkost

Reputation: 8163

django + angularjs resource + ajax POST = 500 (Internal Server Error)

I can do GET requests, but when I do POST, in Chrome developer tools I see: "Failed to load resource: the server responded with a status of 500 (INTERNAL SERVER ERROR)"

I thought the problem is in Django's csrf_token, so I found this solution:

.config(function($httpProvider){
    $httpProvider.defaults.headers.common['X-CSRFToken'] = CSRF_TOKEN;
});

In my index.html, in <head> I have:

<script>
    CSRF_TOKEN = '{{ csrf_token }}';
</script>

But it still raises 500 error. Am I doing something wrong or the problem is not in csrf?

P.S. CSRF_TOKEN is declared before

<script src="{{ STATIC_URL }}lib/angular/angular.js"></script>

and other scripts.

Upvotes: 0

Views: 4097

Answers (3)

A.J.
A.J.

Reputation: 9025

As you all know you need to dump dictionary in your HTTPRESPONCE object.

sometimes what happens, in your view; you try to dump something in to your dict that can not be serialized. that is python/django can not serialize that object.

the examples can be (FORM OBJECT), (MODEL OBJECT), etc

so you need to get those away.

context = {}
context['office_form'] = OfficeCompleteForm(request.POST)

this can not be serialized and you will get 500 error.

be free to add following data.

 context['success'] = {"msg": "successfully updated. "}
 context['error'] = {"msg": "error can not update. "}

and at last do not forget to call you response method like this.

return HttpResponse(json.dumps(context), content_type="application/json")

Upvotes: 0

Pedro Costa
Pedro Costa

Reputation: 1

simply escape the backslash like: /custom_api/get_nearest_hotels/:eventId\/

(From: http://pragmaticstartup.wordpress.com/2013/04/27/some-lessons-learnt-from-messing-with-django-and-angularjs/)

Upvotes: 0

imkost
imkost

Reputation: 8163

I've figured out the problem.

Django by default appends slash to your URL. If you enter:

http://mydjangosite.com/page Django will redirect you to: http://mydjangosite.com/page/

Angular's $resource removes trailing slash (you can read about it on github: https://github.com/angular/angular.js/issues/992).

Django has APPEND_SLASH setting which uses HTTP 302 redirection to append slash to urls without slash. This works with GET method but not with others (POST,PUT,DELETE) because redirection cannot and will not pass the data to the new URL

So, there are two options:

1) Use $http insread of $resource

or

2) In Django's settings.py add this line:

APPEND_SLASH = False

and in your urls.py remove all trailing slashes

Upvotes: 3

Related Questions