Reputation: 771
I've just changed my code from function based views to class based views and now am getting an error I can't seem to resolve.
The error appears when a user presses a button to submit their location coordinates.
Method Not Allowed: /connect/post
[2019/02/11 14:27:17] HTTP POST /connect/post 405 [0.00, 127.0.0.1:57896]
Everything was working before and I can't figure out what I am doing wrong. I have both the get and post
requests. Could someone point me in the right direction?
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>
Upvotes: 4
Views: 6751
Reputation: 16515
You probably are posting to the wrong URL (connect/post/
instead of connect/
). This question has some pointers to check for usual causes of this error.
You could try by changing this line
$.post("post", data, function() {
to
$.post(window.location, data, function() {
Upvotes: 4