6

I am currently making a website using django. Now I want to execute a python script from my template/view with a button on the website. It should be possible but to be honest I don't know how.

An example would be best.

Thanks for any help at all.

asked Sep 29, 2011 at 8:17

4 Answers 4

4

Well got it working now and just thought I would write my answer:

view.py:

import script as gh
def get_hostname(request):
 gh.main()
 return HttpResponseRedirect('/')

urls.py:

... 
url(r'^get_hostname/$', 'thinco.views.get_hostname'), 
...

somewhere in template:

...
 <form action="/get_hostname/" method="GET">
 <input type="submit" value="Liste der Thin Clients laden"> 
 </form>
...
answered Oct 4, 2011 at 7:02
Sign up to request clarification or add additional context in comments.

Comments

4

If you are using Django - best way, IMHO, is just to create the view that will handle your python code, and then access it at onclick event via ajax request.

yourapp/views.py

def your_python_script(request):
 if request.is_ajax:
 # do your stuff here
 ...
 else:
 return HttpRequest(status=400)

If you are using django also you should have jQuery, and in your template add javascript code, something like this:

$("#<your_button_id>").click( function() {
 $.post("your_python_script_url", {<dict with any args you need>}, function () {
 // What to do when request successfully completed
 });
});

And not to forget about CRSF token if your are using it. How to handle it you can find in offical django documentation.

UPDATE

You can add csrf token to page template like:

<script>
var csrf_token = '{% csrf_token %}';
...
</script>

Next, you need to bind to the global jquery ajaxSend event, and add the token to any POST request.

$("body").bind("ajaxSend", function(elm, xhr, s) {
 if (s.type == "POST") {
 xhr.setRequestHeader('X-CSRF-Token', csrf_token);
 }
});

Something like this should work.

answered Sep 29, 2011 at 8:23

5 Comments

Hmm, I didn't really want to use ajax but I understand how you wold do it. Is there another way withut using ajax?
Yes you can find info about embedded python - but that will work only if visitor have some specific plugins/software installed - and by my experience - I haven't seen any people who had such things installed on their machines. And more - a few people will want to install it just to visit your site.
The only way to avoid AJAX is to use static pages. You cannot access any view directly from a template in real time without AJAX. AJAX sort of bridges the gap between View and Template in this paradigm (View and Controller in MVC). For this reason, you need to either send a request via HTML (a form submission, or a URL change) to get a response from the server's python view code or send an AJAX call and have it return something to the page for display.
@Mihail I get a probleme with csrf when I use this method,any idea why?
@astrocybernaute I've added some exaple of CSRF token added automatically to any jQuery ajax post request.
1

Create a view function and do an @dajaxice_register decorator for it:

A silly example follows:

models.py:

class Funkyness(models.Model):
 funktasm = models.CharField(max_length=128)
 funfasticness = models.TextField()

urls.py:

url(r'^funk$', 'views.myFunkyView'),

views.py:

def myFunkyView(request)
 render_to_request('index.htm', {'where': 'home'}, context_instance=RequestContext(request))

index.htm:

{% if where %}
 You are {{ where }}
{% endif %}

When you go to http://yoursite.com/funk, you will get index.htm rendered and you will get a page that says "You are home."

Now, the dynamic part... Write a view method as such:

from django.utils import simplejson
def getHowFunky(request, v):
 html = """
 <div class="my_message">
 This is really funky, almost stinky...
 <br />
 """ + str(v) + """
 </div>
 """
 return simplejson.dumps({'message': html})

back in index.htm:

<script type="text/javascript>
 /* first argument is return JS function, the second is the dictionary of data to sent to the python method. */
 function init(){
 Dajaxice.package.getHowFunky(showFunky, {'v': "Your's Truly... Fubar"});
 }
 function showFunky(data){
 /* This is the data returned back from the AJAX (Dajaxice) call. */
 document.write(data.message)
 }
</script>

So, you build a python method that takes inputs and returns something. You register it with Dajaxice, you call it, passing a callback method. It runs and when it succeeds, it send the python return (possibly JSON object) to the callback method as an argument. That method then writes to the screen what it got from the Dajaxice call.

For more info on Dajaxice, go to: http://dajaxproject.com/

Props to Jorge Bastida, the sole developer of Dajax/Dajaxice!

answered Sep 29, 2011 at 8:48

Comments

0

What I could think of for an answer is to use:

Django + Dajax

Django link: https://docs.djangoproject.com/en/1.4/

Dajax is actually ajax for django: Visit their website and refer to their examples for quick start http://www.dajaxproject.com/

You can create your button in django view and upon triggering your button, you can use run a python snippet, not script.

If you want to run a standalone script, you could probably check out djcelery. http://pypi.python.org/pypi/django-celery

answered Oct 16, 2012 at 14:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.