2

Objects are created using shell while using the same command, but object is not created while I post the data using Angular from another port. I didn't get any errors. I have tried by giving values manually also.

def insertCompany_type(request, *args, **kwargs):
      if request.is_ajax() and request.method == 'POST':
         data = json.loads(request.body)
         c_type = data["subject"]
         user = request.user
         Company_Type.objects.create(user=user, type=c_type)
    return HttpResponse('ok')
Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144
shalin
  • 373
  • 3
  • 19
  • Format the question properly – utkbansal Dec 14 '15 at 11:48
  • while i giving Company_Type.objects.create(user_id =1, type='customer') command in shell, objects are created.. But the same command is not working while posting the data from angular js – shalin Dec 14 '15 at 12:20

1 Answers1

3

You should use some tool like chrome developer tools. See tab "Network" in it. Also you should use decorator csrf_exempt in your code. And, finally, you need to check raw data from user.


@csrf_exempt
def insertCompany_type(request, *args, **kwargs):
    if request.is_ajax() and request.method == 'POST':
        data = json.loads(request.body)
        c_type = data["subject"]
        user = request.user
        Company_Type.objects.create(user = user,type = c_type)
        return JsonResponse({'status': 'ok'})
    return JsonResponse({'status': 'error'})

UPDATE. Yes, i agree. csrf_exempt is a bad idea. Most better add header in request on client side, like that:


angular
  .module('thinkster')
  .run(run);

run.$inject = ['$http'];

/**
* @name run
* @desc Update xsrf $http headers to align with Django's defaults
*/
function run($http) {
  $http.defaults.xsrfHeaderName = 'X-CSRFToken';
  $http.defaults.xsrfCookieName = 'csrftoken';
}

Full version is here

mrvol
  • 2,575
  • 18
  • 21
  • Please do not randomly set @csrf_exempt tag - in your ajax call, set the cookie so you authenticate the request. https://docs.djangoproject.com/en/1.9/ref/csrf/#ajax – ddalex Dec 14 '15 at 11:55
  • thanks for your reply..my question is, while i giving Company_Type.objects.create(user_id =1, type='customer') command in shell, objects are created.. But the same command is not working while posting the data from angular js..print c_type displays the posted value.. Then why objects are not created – shalin Dec 15 '15 at 03:45
  • First of all, you should see your ajax request in Chrome developer tools, like that http://blog.bcdsoftware.com/wp-content/uploads/2013/06/dev-tools-lg.png If you can see it, now you can see detail response, just click on response like that http://stackoverflow.com/questions/8059071/django-are-there-any-tools-tricks-to-use-on-debugging-ajax-response P.S.: Sorry for my english, i'm learning it now. And stackoverflow is good practice ) – mrvol Dec 15 '15 at 08:59