Question

I am creating a website with Django, and I want the user to be able to press a button which will send some data to my server, for example to add an entry to a database with a HTTP post request. I could do this by creating an HTML form, and in the action attribute, point to a view which will do the data processing, and then render a template.

However, what if I do not want to have to render a template? If I want the user to click the button to process some data on the server, but I don't want to render a new template through a view function, how can this be done? I want to maintain the current rendered HTML in the browser, but the only way I know to send data to the server involves rendering a new template in the view function.

Any help? Thanks.

No correct solution

OTHER TIPS

Simply return 204 No Content answer from your view.

Nothing in Django says that a view has to render a template. That's just one of many things a view can do. A view simply needs to return an HttpResponse.

Whether that HttpResponse body contains HTML, etc, is completely up to you. You also don't need a form to post data to your server. You can send any arbitrary data you need simply using JavaScript. You can still use form elements like input, textarea, etc; they don't have to be contained in a form element to be valid.

To make a long answer short, you need to use JavaScript to send data to your Django application via ajax, process the data, and return a response in JSON or XML format, which you can then use to update your page, etc. You can write vanilla JavaScript to do this, or leverage a library like jQuery, or if you're really, really lazy, you can use something like Dajax.

As I said in my previous answer to you, the normal way of doing this in Django is to post to the same view, which accepts the data and then either re-renders the same template (eg to show errors) or redirects to another URL.

Another approach would be to do the post with Ajax.

You can achieve this by send ajax request to your server .
Here you need to write a ajax request which will execute django view and return response into json, xml format .
You can display latest data into your template as per your need.
Ajax request

function mail_check() {
var val = $("#val").val();
$.getJSON('/test/'+val+"/",

function(data) {
// render changes content     
});}

Django view

def checkemailavailability(request, val):
    message = {'result':''}
    if request.is_ajax():
        # put logic here
        #json = simplejson.dumps()   convert data into json
        return HttpResponse(json, mimetype='application/json')

Note : do not forget to include jquery
Links : stackoverflow, tangowith django , bradmontgomery.net

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top