Django AJAX表单,视图中没有POST数据

时间:2014-12-05 13:34:30

标签: ajax django angularjs post

我有一些联系表单和JS / Angular代码发送它来查看某些验证和邮件。

contact_form.js

(function() {
var app = angular.module('contactForm', []);

app.config(function ($httpProvider) {
    $httpProvider.defaults.xsrfCookieName = 'csrftoken';
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
});

app.controller('contactFormController', ['$http', '$scope', function($http, $scope){
    $scope.contact_form = {};
    this.send = function(form){
        if (form.$valid){
            $http.post('/contact_form_submit/', {'form': $scope.contact_form}).
            success(function(data, status, headers, config) {
                if (data.status == 1) {
                    $scope.msg = 'Twoja wiadomość została wysłana.';
                    $scope.contact_form = {};
                    $scope.contactForm.$setPristine();
                }
                else if (data.status == 'delay')
                    $scope.msg = 'Odczekaj.';
            }).
            error(function(data, status, headers, config) {
                $scope.msg = 'Wystąpił błąd.';
                if (status == '403')
                    $scope.msg += ' Włącz cookie!';
            });
        }
        else
            this.msg = 'invalid!';
    };
}]);
})();

view.py

def contact_form_submit(request):
return return_json(request)
if not request.is_ajax() or (request.method != 'POST'):
    raise SuspiciousOperation

response_data = {}

# dealing with existing (or not) delay entry
try:
    if request.session['mailer_delay'] > str(timezone.now()):
        response_data['status'] = 'delay'
        return return_json(response_data)
except KeyError:
    pass

# validation
form_data = {}
for field in ['name', 'email', 'phone', 'subject', 'text']:
    form_data[field] = request.POST.items()

# mailing
mailer = send_mail('Subject here', 'Here is the message.', 'from@example.com',
['to@example.com'], fail_silently=False)
request.session['mailer_delay'] = str(timezone.now()+timedelta(seconds=60))  

response_data['status'] = mailer
return return_json(response_data)

return_json()

def return_json(data):
    from django.http import HttpResponse
    import json
    return HttpResponse(json.dumps(data), content_type="application/json")

问题是我在request.POST中根本没有得到任何项目。 Firebugs告诉我数据发送正确,但是没有看到。 有人知道答案是错的吗?

1 个答案:

答案 0 :(得分:1)

好的,我明白了。所有数据均位于request.body,而不是request.POST。 谁有人解释为什么?我已经阅读了文档,但对我来说还不是很清楚。