How to POST a django form with AJAX & jQuery

后端 未结 6 962
南方客
南方客 2020-11-28 00:49

I\'ve checked out tons of tutorials for django AJAX forms, but each one of them tells you one way of doing it, none of them is simple and I\'m a bit confused since I\'ve nev

6条回答
  •  情深已故
    2020-11-28 01:44

    On the server side, your django code can process the AJAX post the same way it processes other form submissions. For example,

    views.py

    def save_note(request, space_name):
    
        """
        Saves the note content and position within the table.
        """
        place = get_object_or_404(Space, url=space_name)
        note_form = NoteForm(request.POST or None)
    
        if request.method == "POST" and request.is_ajax():        
            print request.POST
            if note_form.is_valid():
                note_form.save()
                msg="AJAX submission saved"
            else:
                msg="AJAX post invalid"
        else:
            msg = "GET petitions are not allowed for this view."
    
        return HttpResponse(msg)
    

    I've assumed your NoteForm is a ModelForm -- which it should be -- so it has a save method. Note that in addition to adding the save() command, I changed your request.is_ajax to request.is_ajax(), which is what you want (if you use request.is_ajax your code will just check whether the request has a method called is_ajax, which obviously it does).

提交回复
热议问题