【问题标题】:Storing ajax post data in django model在 Django 模型中存储 ajax 发布数据
【发布时间】:2015-12-14 11:43:40
【问题描述】:

对象是在使用相同命令时使用 shell 创建的,但在我使用 Angular 从另一个端口发布数据时不会创建对象。我没有收到任何错误。我也尝试过手动给出值。

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

【问题讨论】:

  • 正确格式化问题
  • 当我在 shell 中给出 Company_Type.objects.create(user_id =1, type='customer') 命令时,创建了对象。但是从 angular js 发布数据时,相同的命令不起作用

标签: angularjs django


【解决方案1】:

您应该使用一些工具,例如 chrome 开发人员工具。请参阅其中的“网络”选项卡。你也应该在你的代码中使用装饰器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'})

更新。是的我同意。 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

【讨论】:

  • 请不要随意设置@csrf_exempt 标记——在您的ajax 调用中,设置cookie 以便您对请求进行身份验证。 docs.djangoproject.com/en/1.9/ref/csrf/#ajax
  • 感谢您的回复..我的问题是,当我在 shell 中给出 Company_Type.objects.create(user_id =1, type='customer') 命令时,会创建对象.. 但是同样的命令从 Angular js..print c_type 发布数据时不起作用..print c_type 显示发布的值.. 那么为什么没有创建对象
  • 首先,你应该在 Chrome 开发者工具中看到你的 ajax 请求,像 blog.bcdsoftware.com/wp-content/uploads/2013/06/… 如果你能看到它,现在你可以看到详细的响应,只需点击像 stackoverflow.com/questions/8059071/… 这样的响应P.S.:对不起我的英语,我现在正在学习它。而且stackoverflow是很好的做法)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-10
相关资源
最近更新 更多