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')
2
  • Format the question properly Commented Dec 14, 2015 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 Commented Dec 14, 2015 at 12:20

1 Answer 1

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

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

3 Comments

Please do not randomly set @csrf_exempt tag - in your ajax call, set the cookie so you authenticate the request. docs.djangoproject.com/en/1.9/ref/csrf/#ajax
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
First of all, you should see your ajax request in Chrome developer tools, like that blog.bcdsoftware.com/wp-content/uploads/2013/06/… If you can see it, now you can see detail response, just click on response like that stackoverflow.com/questions/8059071/… P.S.: Sorry for my english, i'm learning it now. And stackoverflow is good practice )

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.