我在请求一个 url 时使用 Django 编写一个项目,我得到一个奇怪的 Not Allowed Mthod(405)。我的错误是什么,但这是我的实现和细节:
网址.py
url(r'^join/',
csrf_protect(UserSignUp.as_view()),
name='sgn_up'),
视图.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!
我还有其他带有 csrftokens 的 ajax 发布请求,它们也可以正常工作(例如登录)!
最有趣的是,当我使用 Chrome 时它会给出错误,并且用户数据也保存在数据库中!!!(这意味着模型发布方法有效!!!)但是当使用 firefox 时它只会给出错误!
有没有人遇到过这样的问题?我搜索了很多,但没有发现任何帮助!
谢谢