Danial Ahmed
Danial Ahmed

Reputation: 866

Unable to POST data to django function using ajax

I am trying to add data and view data to/from django database through AJAX calls, fetching data works fine but adding data doesnt work. I getting following error:

Method Not Allowed (POST): /mymodels/
Method Not Allowed: /mymodels/
[17/Mar/2020 22:27:24] "POST /mymodels/ HTTP/1.1" 405 0

and in browser console:

0: undefined

My ajax function:

$(document).on('submit', '#myform', function(e){
    $.ajax({
        type: 'POST',
        url: `/mymodels/create`,
        data:{
            first_name:$('#first_name').val(),
            last_name:$('#last_name').val(),
            age:$('#age').val()
        },
        success:function(json){
            console.log("Data submitted");
        },
        error:function(xhr,errmsg,err)
        {
            console.log(xhr.status + ": " + xhr.responseText);
        }
    })
})

urls.py:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('mymodels/', TemplateView.as_view(template_name='crud_app/main.html'),name='mymodel_main'),
    path('mymodels/list', views.MyModelList.as_view(), name='mymodel_list'),
    path('mymodels/create', views.MyModelCreate.as_view(), name='mymodel_create'),
    path('mymodels/update/<int:pk>', views.MyModelUpdate.as_view(), name='mymodel_update'),
    path('mymodels/delete/<int:pk>', views.MyModelDelete.as_view(), name='mymodel_delete'),
    path('mymodels/<int:pk>', views.MyModelDetail.as_view(), name='mymodel_detail'),
]

view:

class MyModelCreate(CreateView):
    def post(self,request):
        data = dict()
        form = MyModelForm(request.POST)
        if form.is_valid():
            my_model = form.save()
            data['my_model'] = model_to_dict(my_model)
        else:
            data['error'] = 'Form invlaid'
        return JsonResponse(data)

and finally my html form:

<form class="form-group" id="myform" method="POST">
{% csrf_token %}
  <label for="first_name">First Name</label>
  <input type="text" class="form-control" name="" id="first_name" placeholder="">
  <label for="last_name">Last Name</label>
  <input type="text" class="form-control" name="" id="age_name" placeholder="">
  <label for="age">age</label>
  <input type="text" class="form-control" name="" id="age" placeholder="">
  <input  type="submit" class="btnSubmit btn btn-primary" value="Submit">
</form>
{% endblock %}

{% block extrajs %}
<script src="{% static 'js/app.js' %}"></script>
{% endblock %}

Upvotes: 1

Views: 53

Answers (2)

Prince Raj
Prince Raj

Reputation: 52

your ajax code need some improvement change your ajax code to this..

    $(document).on('submit', '#myform', function(e){
    e.preventDefault()
   var formAction = $('#myform').attr('action')
       $.ajax({
           url: formAction,
           data: $('#myform').serialize(),
           type: 'POST',
           success:function(json){
               console.log("Data submitted");
           },
           error:function(xhr,errmsg,err){
               console.log(xhr.status + ": " + xhr.responseText);
           }
                });
            });

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477318

You need to pass the csrf token in the request. You can ship this with:

$(document).on('submit', '#myform', function(e){
    $.ajax({
        type: 'POST',
        url: `/mymodels/create`,
        data:{
            first_name:$('#first_name').val(),
            last_name:$('#last_name').val(),
            age:$('#age').val(),
            csrfmiddlewaretoken: '{{ csrf_token }}'
        },
        success:function(json){
            console.log("Data submitted");
        },
        error:function(xhr,errmsg,err)
        {
            console.log(xhr.status + ": " + xhr.responseText);
        }
    })
})

Upvotes: 0

Related Questions