[Django]-How can I run a Django function on a button press which doesn't render content?

4👍

If you use a normal form POST, the page will reload – that’s just how HTTP works. To have a ‘background’ POST, you need to use AJAX. If you have jQuery on your page, you’ll want to add an ID to your form so it can be easily selected, then do something like this:

$("#formid").bind("submit", function(){
    $.post(ajax_url, {r: $(this).find('[name="r"]').val()}, function(data){
        // nothing here for now, but this is where you could update the UI, etc.
    });
    return false;
});

Here are the relevant jQuery docs.

In your view, you can conditionally dispatch to the refreshing function based on request.is_ajax() (or any other condition, say, whether a particular POST key provided by a hidden input is present):

def your_view(request):
    if request.is_ajax(): return updateRevFromS3(request)
    elif request.POST.get("my-hidden-input-name") == "this-is-the-update-form":
        return updateRevFromS3(request)
    return normal_processing()
👤AdamKG

1👍

If you don’t want a page reload, the easiest way to do this is by having some JavaScript that performs the HTTP request for you. Take a look at jquery, it’s a JS library that makes things like this a breeze.

Leave a comment