Print output to a Django webpage

I currently have a long script that produces different output. What I want to do is run this script when a button is clicked on my web server, and for the output to be displayed in real time in the text area of ​​the web page. I was wondering how to do this using Django.

+6
source share
2 answers

You need a WebSocket ! Django is not directly supported, but I would recommend taking a look at Websockets for Django applications using Redis . I have used this before and it is very easy to configure and use.

For example, create a django template (e.g. output.html ):

 <html> ... <body> <textarea id="output" row=3 cols=25></textarea> <script> var ws = new WebSocket('{{ ws_url }}'); ws.onmessage = function(e) { $('#output').append(e.data); }; </script> </body> </html> 

Then create a method that will call your script when it wants to display the message in the text area:

 def output_message(session_key, user, message): conn = redis.StrictRedis() ws_url = '{0}:{1}'.format(session_key, user) conn.publish(ws_url, message) 

And finally, you need to specify in your views.py method that displays your output.html template:

 def output_console(request): template_values = {'ws_url':'ws://{SERVER_NAME}:{SERVER_PORT}/ws/{0}?subscribe-session'.format(request.user.id, **request.META)} return render(request, 'output.html', template_values) 

Check out the chat server for git repo projects for a more in-depth sample code.

Hope this helps and good luck!

+1
source

If you are talking about real-time output, you need to use AJAX.

To install the script, on the web page you can get a button that sends an AJAX request.

 function ajax_call_model(data_JSON_Request, object_id){ $(function jQuery_AJAX_model(){ $.ajax({ type: 'GET', url: '/ajax_request/', data: something, datatype: "json", success: function(data) { $("#output_id").html(data); },//success error: function() {alert("failed...");} });//.ajax });//jQuery_AJAX };//ajax_call 

In the views you will have something like this:

 def ajax_request(request): something = request.GET.get('something', '')# Receives from AJAX output = #Does something with the request jsonDump = json.dumps(str(output)) return HttpResponse(jsonDump, content_type='application/json') 
0
source

All Articles