我刚刚将代码从基于函数的视图更改为基于类的视图,现在遇到了我似乎无法解决的错误。
当用户按下按钮提交其位置坐标时,会出现错误。
Method Not Allowed: /connect/post
[2019/02/11 14:27:17] HTTP POST /connect/post 405 [0.00, 127.0.0.1:57896]
之前所有工作都在进行,我无法弄清楚自己在做什么错。我有两个get and post
请求。有人可以指出我正确的方向吗?
views.py
class ConnectView(View):
template_name = 'connect/home.html'
def get(self, request, *args, **kwargs):
context = {
'users': User.objects.exclude(username=request.user),
}
return render(request, self.template_name, context)
def post(self, request, *args, **kwargs):
location = Location(latitude=request.POST['latitude'],
longitude=request.POST['longitude'], user = request.user)
location.save()
return JsonResponse({'message': 'success'})
urls.py
urlpatterns = [
path('', connect_views.ConnectView.as_view(), name='connect_home'),
]
connect.html
<script>
function showPosition(position) {
pos = position;
var { latitude, longitude } = pos.coords;
$('#btn_submit').attr("disabled", null);
}
$(document).ready(function() {
$demo = $("#demo");
$('#btn_submit').on('click', function() {
var data = pos.coords;
data.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val();
$.post("post", data, function() {
alert("Location Confirmed!");
});
});
});
</script>
---omitted irrelevant code--
<button type="submit" id="btn_submit" class="btn btn-success" disabled>2. Confirm Location </button>
答案 0 :(得分:2)
您可能发布到错误的URL(connect/post/
而不是connect/
)。 This question有一些指针可以检查导致此错误的常见原因。
您可以尝试更改此行
$.post("post", data, function() {
到
$.post(window.location, data, function() {