我刚刚将我的代码从基于函数的视图更改为基于类的视图,现在出现了一个无法解决的错误。
当用户按下提交他们的位置坐标按钮时,错误会出现。
Method Not Allowed: /connect/post
[2019/02/11 14:27:17] HTTP POST /connect/post 405 [0.00, 127.0.0.1:57896]
之前一切正常,但我无法弄清楚我做错了什么。我有get和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>
connect/
)。这里有一个类似的问题,其中提供了一些检查此类错误常见原因的指针。 - Ralf