2015-12-14 24 views
2

雖然使用相同命令時使用shell創建了對象,但在使用來自另一個端口的Angular發佈數據時並未創建對象。我沒有得到任何錯誤。我也嘗試通過手動賦值。在django模型中存儲ajax發佈的數據

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') 
+0

格式問題妥善 – utkbansal

+0

而我給Company_Type.objects.create(USER_ID = 1,類型=「客戶」 )命令在shell中創建對象..但是,在從角度js發佈數據時,相同的命令不起作用 – shalin

回答

3

你應該使用一些工具,如鉻開發工具。請參閱標籤中的「網絡」。你也應該在代碼中使用修飾器csrf_exempt。最後,您需要檢查用戶的原始數據。


@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。是的我同意。 csrf_exempt是一個壞主意。大多數更好地請求添加頁眉上的客戶端,這樣的:


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'; 
} 

完整版是here

+0

請不要隨意設置@csrf_exempt標記 - 在您的ajax調用中,設置cookie以便驗證請求。 https://docs.djangoproject.com/en/1.9/ref/csrf/#ajax – ddalex

+0

我已經更新了我的答案。謝謝! – mrvol

+0

感謝您的答覆..我的問題是,雖然我給殼Company_Type.objects.create(user_id = 1,鍵入='客戶')命令,對象創建..但同一命令不工作時發佈的數據從角度js..print c_type顯示發佈的值..然後爲什麼不創建對象 – shalin