2👍
✅
Whenever you are using Django and Ajax, you should be thinking of a rest framework (like Django Rest Framework). Hand-rolling your own ajax & endpoints is reinventing the wheel, while other very smart people have open sourced their code for you. Using a framework with Ajax lets you break your model manipulation out of the Django request-response cycle and handle things really easily in the browser.
There are 3 steps:
- Install DRF and set up some model endpoints
- Write the ajax request to hit your endpoint
- Manipulate the DOM based on the response.
Example template:
template.html
{% block extra_js %}
<script type="text/javascript">
// Forgive the pseudocode, I have not run this.
// Uses jquery because everything does.
// For each item in an array, add it to a selected table in a new row
var do_dom_manipulation = function(data){
$.each(data, function(d){
$('table.mytable').append('<tr>'+d+'<tr>')
})
}
// Hit the rest endpoint to get data from the browser
$.ajax('api/models',
{
'name': 'foo'
}
).done(function(data) {
alert( "success" );
do_dom_manipulation(data)
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
</script>
{% endblock extra_js %}
1👍
Try using
import django.utils.simplejson as json
json.dumps(prod_serv)
OR you can use serializer
from django.core import serializers
# serialize queryset
serialized_queryset = serializers.serialize('json', prod_serv)
Source:stackexchange.com