Asynchronous forms with bootstrap and django

后端 未结 1 634
遥遥无期
遥遥无期 2020-12-16 08:01

So i\'m trying to make this form asyncronous. Ideally, I\'m using this form to add units, and then update the table dynamically. I do not want the entire page to refresh. I\

1条回答
  •  自闭症患者
    2020-12-16 08:20

    I struggled horribly with AJAX when I started with Django due to a lack of JS experience.

    I will give you an example of an aync form I use to add options and display the options.

    My template modal code is as follows, and it will work just as well with the form being rendered rather than my lazy hardcoded html.

       
    

    Next, make sure that the following is in your to take care of CSRF token issues.

    
    

    Second, this is what a basic AJAX POST would look like using jQuery. Notice it is based on preventing the Default submission behaviour of the form living in our modal. On success I am appending the newly added values to the table. It would be less troublesome to add the values as part of catching the form, but I like to be sure everything has been saved and processed before being added to the table.

       $(document).ready(function() {
       $("#OptionForm").submit(function(event){
           event.preventDefault();
           $.ajax({
                type:"POST",
                url:"{% url builder.views.addoption %}",
                data: {VariableID: $('input:hidden[name=VariableID]').val(), OptionLabel: $('input:text[name=OptionLabel]').val(), OptionValue: $('input:text[name=OptionValue]').val()},
                success: function(data){
                console.log(data['OptionID']);
                $("#OptionValueError").removeClass("error");  
                $("#OptionValueError span").text("");  
                $("#OptionValueError span").removeClass("error");
                $('#OptionTable > tbody:last').append(''+data['OptionValue']+''+data['OptionLabel']+'');
                $('input:text[name=OptionValue]').val('');
                $('input:text[name=OptionLabel]').val('');
                }
              });
           });
        });
    

    Lastly, you just need the view that captures this AJAX request, which would look like this partially written one below.

    def addoption(request):
        if request.is_ajax():
            OptionValue = int(request.POST['OptionValue'])
            OptionLabel = request.POST['OptionLabel']
            VariableID = int(request.POST['VariableID'])
            getVar = Variable.objects.get(id=VariableID)
            newOption = Option(VariableID=getVar,
                    Value=OptionValue,
                    Label=OptionLabel)
            newOption.save()
            response = {'OptionValue': OptionValue, 'OptionLabel': OptionLabel, 'OptionID': newOption.id}
            json = simplejson.dumps(response)
            return HttpResponse(json, mimetype="text/json")
        else:
            pass
    

    The response dict that we are json serializing is what is fed back as data and subsequently used to append the values to the table. All without reloading the main page.

    Hopefully the example helped. Let me know if you have anymore questions.

    JD

    0 讨论(0)
提交回复
热议问题