Django奇怪的方法是不允许的

时间:2013-11-03 09:52:39

标签: ajax django jquery django-views django-urls


我在使用Django编写项目时请求一个url我得到一个奇怪的Not Allowed Mthod(405)。 我的错误是什么,但这是我的实现和细节:

urls.py

url(r'^join/',
        csrf_protect(UserSignUp.as_view()),
        name='sgn_up'),

views.py

class UserSignUp(View):

    def post(self, request):
        resp_data = {}
        try:
            print 'sign up================================================'
            x = MyUser.objects.get(email=request.POST['email'])
            resp_data['message'] = 'signed up before'
            return HttpResponse(json.dumps(resp_data), content_type="application/json")

        except MyUser.DoesNotExist:
            user = MyUser(email=request.POST['email'],
                          password=request.POST['password'],
                          first_name=request.POST['firstName'],
                          last_name=request.POST['lastName']
                          )
            user.save()
            #print 'errorize'
            user.set_password(request.POST['password'])
            user.save()
            resp_data[
                'message'] = 'please refer to your email for complete registrations'
            return HttpResponse(json.dumps(resp_data), content_type="application/json")

HTML / JS

function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    var csrftoken = $('input[name="csrfmiddlewaretoken"]').prop('value');
    function sameOrigin(url) {
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });
    function ajaxSignIn(){
        $.ajax({
            url:"{% url 'sgn_in' %}",
            type: "POST",
            data: $('#sgn-in-form').serialize(),
            dataType : "json",
            success: function(json){location.reload();},
            error: function(xhr, status) {}
        });
    }
    function ajaxSignUp(){
        $.ajax({
            url:"{% url 'sgn_up' %}",
            type: "POST",
            data: $('#sgn-up-form').serialize(),
            dataType : "json",
            success: function(json){location.reload();},
            error: function(xhr, status) {}
        });
    }

现在我发送一个ajax请求(我已经包含了csrftoken)和post方法但是我得到了一个405! 我还有其他ajax发布请求与csrftokens bur他们也工作(例如登录)!

关于这一点最有趣的是,当我使用Chrome时它会给出错误并且用户数据也会保存在DB !!!中(这意味着模型post方法有效!!!)但是当使用firefox时它只给出错误!
有没有人遇到过这样的问题?我搜索了很多,但没有找到任何帮助! 谢谢

1 个答案:

答案 0 :(得分:0)

在您的def帖子中,您还必须包含上下文。

    self.object = self.get_object()
    context = self.get_context_data(object=self.object)
    return self.render_to_response(context)`