django: taking input and showing output in the same page

后端 未结 4 1404
Happy的楠姐
Happy的楠姐 2020-12-25 08:15

I am quite new to django and struggling to do something very simple. I have a ModelForm for the following model:

class Queries(models.Model):
         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-25 08:49

    Following Hoff's answer...

    Add URL attribute to ajax call:

    $(document).ready(function() {
        $("#myForm").submit(function() { // catch the form's submit event
            $.ajax({ // create an AJAX call...
                data: $(this).serialize(), // get the form data
                type: $(this).attr('GET'),
                url: '/URL-to-ajax-view/',
                success: function(response) { // on success..
                    $("#response").html(response); // update the DIV
                }
            });
            return false;
        });
    });
    

    Some ajax handler in views.py:

    # /URL-to-ajax-view/
    def ajax_get_response(request):
        if request.method == "GET" and request.is_ajax:
            form = QueryForm(request.POST or None)
            if form.is_valid():
                form.save()
                return HttpResponse(form.response)  
        raise Http404
    

    Tried something like that?

提交回复
热议问题