Django, Update Part Of The Page
Solution 1:
In case you are looking for code to auto-update a field in HTML here is the code which you could use. The setInterval in JavaScript schedules get_log view to be pulled every 1 second for result of get_log_from_disk method.
urls.py
url(r'^get_log/$', 'myapp.views.get_log', name='get_log'),
url(r'^submit/$', 'myapp.views.submit', name='submit'),
views.py
def submit(request):
## Handle POST
## Your code comes here
return render(request, 'submit.html', {})
def get_log_from_disk():
## Your code comes here
return "Test 1 OK; Test 2 OK"
def get_log(request):
results = get_log_from_disk()
return HttpResponse(results)
in submit.html add
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
[<div id="output_box"></div>]
<script>
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
var my_refresh = setInterval(function() {
$('#output_box').load('/get_log/');
}, 1000); // the "1000"
});
</script>
</body>
You could modify "$('#output_box').load('/get_log/');" to test for status of request and when "204 No Content" is returned you can remove the function (clearInterval(my_refresh );)
see Stop setInterval call in JavaScript
Modify get_log view to return "204 No Content" when there is no more content to be sent.
Here I have uploaded working version
https://github.com/lukaszszajkowski/Django-jQuery-Example-update-part-of-page/tree/master
Some reading
Auto-refreshing div with jQuery - setTimeout or another method?
Solution 2:
This could be what you are looking for:
var ajaxForm = function() {
$.ajax({
type: 'POST',
contentType: 'application/json',
dataType: 'json',
url: '/path/to/django/controller',
// The data sent to the Django view in JSON format
data: JSON.stringify({
formField: $('#body').val()
}),
success: function (data) {
$('#output-box').html(data);
}
});
}
$('#form').on('submit', function (e) {
e.preventDefault();
ajaxForm();
});
The implementation of a Django controller can be something like:
import json
from django.http import HttpResponse
def ajax_view(request):
if request.method == 'POST':
request_data = json.load(request.raw_post_data)
# do something
response_data = {}
response_data['result'] = 'Failed'
response_data['message'] = 'Your test not ended well'
return HttpResponse(
json.dumps(response_data),
content_type='application/json'
)
Post a Comment for "Django, Update Part Of The Page"