alacy
alacy

Reputation: 5074

How to call a specific python function from within a Django template

I have a button to copy data from a user uploaded file to the clipboard in a specific format. I already have that data saved in the database as it was uploaded in a separate file form. I currently have it so that upon clicking the copy to clipboard button it is linked to a copy_data view in my views.py that requires an HTTP request which redirects to the current template containing the copy to clipboard button with something like this:

HttpResponseRedirect('previous/template/here')

This works fine except for the fact that since it links to my copy_data view which then redirects to the original view containing the button it reloads the entire page which is undesirable.

I think a better solution would be to somehow bind a python function directly to the button click rather than worrying about redirecting from one view to another.

I've found many examples using ajax, but haven't found any that work for my use case. I tried binding a click event to the button without any problems, but I am stuck on figuring out how to bind the python function with the click.

How can I bind a python function in my Django template upon a button press?

Upvotes: 1

Views: 806

Answers (1)

dylrei
dylrei

Reputation: 1738

It's tough to tell for sure, but I think you're mixing synch/asynch paradigms here. When you generate requests with Ajax, you don't (generally) want to return a redirect, you want to return data. That might be JSON data or data formatted as a specific MIME type or even just text. One way this might look at a high level is:

def copy_data(request):
    # get posted data
    submitted = request.POST
    # do whatever is necessary to create document
    data = ???
    # first, we'll need a response
    resp = HttpResponse() 
    # set the content type, if needed
    resp.content_type = 'text/???; charset=utf-8'
    # response has a file-like interface
    resp.write(data)
    return resp

Obviously, this would need work to suit your purpose, but that's the high-level approach.

It doesn't sound like you're returning JSON, but there's a special response object for that now if you need it.

Upvotes: 1

Related Questions