Django form validation using Ajax and multiple sub

2019-04-16 17:39发布

So far I have succeeded in implementing this view using dajax, but I find it very messy and as I've been reading so far it is good practice to have your view, well, in the view.py file. I've tried implementing it using this guide: http://www.micahcarrick.com/ajax-form-submission-django.html but without being able to read which button is clicked.

The same view shall still be shown after submitting (no redirection) as the page also contains plotting and other statuses of my connected instruments.

models.py

class ActiveMeas(models.Model):
    channels    = models.CharField(max_length=100)
    technology  = models.ForeignKey(TechnologyModel)
    samples     = models.IntegerField()
    delay       = models.IntegerField()
    table       = models.IntegerField()
    stir        = models.IntegerField()

forms.py

class ActiveForm(ModelForm):
    class Meta:
        model=ActiveMeas

html file

<form action="" method="post" id="activeform">
    <div id="ajaxwrapper">
    {% csrf_token %}
    {{ form.non_field_errors }}
    {{ form.as_p }}
    <p id="sendwrapper"><input type="submit" value="Start" id="idstartbut" name="_ButtonStart"/></p>
    <p id="sendwrapper"><input type="submit" value="Stop" id="idstopbut" name="_ButtonStop"/></p>
    </div>
</form>

And the view file where I never get into the buttonstart or buttonstop. Another question is how do I return data to the javascript and update it from there?

views.py

def active(request):
    if request.POST:
        form = ActiveForm(request.POST)
        if '_ButtonStart' in request.POST:
            print "START"
            if form.is_valid():
                response_data = {'data':request.POST}
                return HttpResponse(simplejson.dumps(response_data))
            else:
                print "NOT VALID"
                response_data = {'data':request.POST}
                return HttpResponse(simplejson.dumps(response_data))
        elif '_ButtonStop' in request.POST:
            print "STOP"
    else:
        form = ActiveForm()
    return render(request, 'active.html', {'index': "active",'form':form})

javascript

function ActiveInit(){
    $(document).ready(function () {
    $(function() {
        var form = $("#activeform");
        form.submit(function(e) {
            $("#ajaxwrapper").load(
                form.attr('action') + ' #ajaxwrapper',
                form.serializeArray(),
            );
            e.preventDefault(); 
        });
    });
}

I'm very new to both django, ajax and jQuery. So please enlighten me if something is to be done different, and how to solve my problem.

2条回答
老娘就宠你
2楼-- · 2019-04-16 18:02

After quiet some more searching, I found the jQuery form plugin http://www.malsup.com/jquery/form/ which does exacly what I wanted.

So simply my javascript is now:

$(document).ready(function(){
    $('#aform').ajaxForm(function(data){
        if(data){
              //Do something with the returned data
        }
    });
});

Which both sends the form and submit value to my view.

My view function then dumps the errors to jQuery for then to be shown if any

if request.POST:
    form = ActiveForm(request.POST)
    if form.is_valid():
        errors=""
        if '_ButtonStart' in request.POST:
            print "START"
        elif '_ButtonStop' in request.POST:
            print "STOP"
    else:
        print "NOT VALID stop"
        errors=form.errors
    return HttpResponse(simplejson.dumps(errors))
else:
    form = ActiveForm()
    return render(request, 'active.html', {'index': "active",'form':form})

In javascript, the errors can then be read by:

var errors = $.parseJSON(data);
console.log(errors.samples);     //Samples is an inputbox in my form 
查看更多
萌系小妹纸
3楼-- · 2019-04-16 18:19

there is nothing different to submitting form with ajax or without.

In one case browser takes care of everything and puts together query sent to server, in case of ajax, all that is done by javascript - jQuery in your case.

Look at this:http://api.jquery.com/jQuery.post/

Now how about to get returned validating data back from django?

There are 2 approaches:

1) Return rendered template of a form and just replace existing from with returned form. In that case you need to render all error messages in that template. take a look at these links: http://djangosnippets.org/snippets/1094/ How do I display the Django '__all__' form errors in the template?

2) In second case you can manually put together list of all form errors on django side. turn them into json and then write script that matches errors with elements on website and then shows them.

If you are new to jquery and django then 1) is much easyer to do that 2)

Good luck

查看更多
登录 后发表回答