POST to URL from template

I’m trying to POST to a URL using a button on the Django template. But between clicking the button and posting to the URL – I also need to get the POST payload from a view method. I’ll try to write some code here and explain side by side of what my goal is.

Let’s assume there is a hidden form and a hidden input field that will actually get submitted to POST the payload to the external URL. Here’s the sample for the form and input field:

<form action="{{license_server_url}}" id="form_{{}}" 
    method="post" target="_blank">
    <input id="form_input_{{}}" 

In addition to the form, there’s this button somewhere in the template that is supposed to be the trigger point.

<button onclick="jsFuncGetPayload('form_{{}}', 
    '{% url getLicenseFileString}');" 
    title="Generate License File">

        <img align="absmiddle" 
            alt="Generate License File">

Now, the function jsFuncGetData takes the form Id, hidden input Id and the django URL (where an AJAX call will be made to get the POST payload that will be used to submit to the external form submit).

function jsFuncGetPayload(form_id, input_id, url) {
	form = '#' + form_id;
	input = form + ' #' + input_id; // Get input under the form Id
	//set async equal to false (default is true) to get it to wait 
          //for the call to complete before submitting to license server
		type: "GET",
		url: url,
		dataType: "text",
		async: false
		.done(function(data) {
			$(input).val(data); // Save response in hidden input
	//if there is no filexkey then the call to ge the license file from django returns an empty string
	if ($(input).val()) {
	else {
		alert('You must have a FilexKey to generate a license file.');

Here’s the URL config in Django that is used to get the POST payload:

url(r'^appid/get_license_file/(?P<appid_id>\d+)/$', 'getLicenseFileString', name='getLicenseFileString'),

View to get the license string in Django:

def getLicenseFileString(request, appid_id):
    get the license file string and just return the string
    appid = Appid.objects.select_related().get(pk=appid_id)
    if appid.filexkey:
        return HttpResponse(appid.generateLicenseFileString())
        return HttpResponse('') #return nothing if there is no filex key

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s