3👍
✅
You can do this usnig AJAX
Fisrt of all you have to define an AJAX view:
from .model import Customer# import here your model
from django.http.response import JsonResponse
from django.shortcuts import get_object_or_404
def ajax_view(request):
results = {}
if request.method == 'POST':
pk = request.POST.get('pk',None)
if pk:
customer = get_object_or_404(Customer, id=pk)
results['code'] = 200
if customer.is_active:
customer.is_active = False
results['status'] = 'inactive'
else:
customer.is_active = True
results['status'] = 'active'
customer.save()
else:
results['code'] = 404
else:
results['code'] = 500
return JsonResponse(results)
Then create a new url in urls.py
:
url(r'^activeConsumer$', views.ajax_view, name ="active_consumer"),
After that in your Template you define an AJAX call using JQuery
:
<script>
function active_consumer(id) {
//AJAX DATA
//you have to send data to server
// first you have to get the id of the consumer
// second you have to pass `csrfmiddlewaretoken` with data
data = {
'pk':id,
'csrfmiddlewaretoken' : '{{csrf_token}}' };
//AJAX CALL
$.post( "{% url 'active_consumer' %}", data).done(function(response) {
if (response.code == 200) {
if (response.status == "active") {
//here you have to change the status of the consumer to active in HTML
}
else {
//here you have to change the status of the consumer to inactive in HTML
}
}
});
}
</script>
In your HTML you make a call to the javascript function active_consumer
:
<button name="button" value="OK" type="button" onclick="active_consumer({{lead.id}})" >change status</button>
UPDATE:
to check or uncheck the radio button , you must give it an id
:
{% if lead.is_active %}
<input id="myradio" type="radio" value="" checked>
{% else %}
<input id="myradio" type="radio" value="" >
{% endif %}
To check the radio button using JQuery
:
$("#myradio").prop("checked", true)
To uncheck it:
$("#myradio").prop("checked", false)
So the javascript function will be like this:
<script>
function active_consumer(id) {
data = {
'pk':id,
'csrfmiddlewaretoken' : '{{csrf_token}}' };
$.post( "{% url 'active_consumer' %}", data).done(function(response) {
if (response.code == 200) {
if (response.status == "active") {
//uncheck the radio button
$("#myradio").prop("checked", false)
}
else {
//check the radio button
$("#myradio").prop("checked", true)
}
}
});
}
</script>
Source:stackexchange.com