Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data from Ajax POST in my django views function?

Tags:

django

$(document).ready(function(){  
  $('.addFolder input').keydown(function(e) {
    if (e.keyCode == 13) {
        name = $(this).val();
        $.ajax({
          type: "POST",
          url: "/folder/",
          data: name,
            success: function(result) {
              $('.folders ul li:first-child').after('<li class="bg-color-2 ui-droppable" data-folderid="2">'+name+' <span>0</span></li>');
              $('.addFolder input').val('');
            }
        });
    }
  });

How to get data from this Ajax post in my django views function?

templates:

  <div class="addFolder">
    <span>+</span>
    <input type="text" placeholder="Folder's name">

  </div>

views:

def folder(request):
    user = request.user
    if request.method == "POST" and request.is_ajax():
        name = request.POST['name']
        f = Folder.objects.create(name=name, user=user)
        status = "Good"
        return HttpResponse(status)
    else:
        status= "Bad" 
        return HttpResponse(status)

Why still I have:

[30/Nov/2013 14:47:52] "POST /folder/ HTTP/1.1" 403 2294

in logs?

like image 300
netman97 Avatar asked Nov 30 '13 14:11

netman97


1 Answers

You can always access it in your request.POST variable.
Docs: link

Another thing you should fix in js code is data parameter.
jQuery docs state the following: Object must be Key/Value pairs (link)

on updated question
You receive 403 because you're not sending csrf token.
If you have 'django.middleware.csrf.CsrfViewMiddleware' enabled in your MIDDLEWARE_CLASSES, then you'd need to put {% csrf_token %} into your form's template, and then send it via js along with your data.
Like this: data: {'name': name, 'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val()}

like image 122
Alex Parakhnevich Avatar answered Nov 01 '22 06:11

Alex Parakhnevich