Angularjs 在django模型中存储ajax post数据
对象是在使用同一命令时使用shell创建的,但在我从另一个端口使用Angular发布数据时不会创建对象。我没有收到任何错误。我也尝试过手动赋值Angularjs 在django模型中存储ajax post数据,angularjs,django,Angularjs,Django,对象是在使用同一命令时使用shell创建的,但在我从另一个端口使用Angular发布数据时不会创建对象。我没有收到任何错误。我也尝试过手动赋值 def insertCompany_type(request, *args, **kwargs): if request.is_ajax() and request.method == 'POST': data = json.loads(request.body) c_type = data["subjec
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')
你应该使用一些工具,比如chrome开发者工具。请参阅其中的“网络”选项卡。此外,您还应该在代码中使用decorator
csrf\u-emption
。最后,您需要检查来自用户的原始数据
@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'})
更新。是的,我同意。csrf_豁免是个坏主意。最好在客户端的请求中添加头,如下所示:
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';
}
完整版本是正确设置问题格式,当我在shell中给Company_Type.objects.create(user_id=1,Type='customer')命令时,将创建对象。。但是,在发布来自angular JS的数据时,相同的命令不起作用。请不要随机设置@csrf_-emption标记-在ajax调用中,设置cookie以便对请求进行身份验证。谢谢你的回答。我的问题是,当我在shell中给Company_Type.objects.create(user_id=1,Type='customer')命令时,对象被创建了。。但是,从angular js发布数据时,同一命令不起作用。print c_type显示发布的值。。那么为什么不创建对象首先,你应该在Chrome开发者工具中看到你的ajax请求,就像这样,如果你能看到它,现在你可以看到详细的响应,只需点击像这样的响应:对不起,我的英语,我正在学习。并且stackoverflow是一种良好的做法)