I am trying to implement a function in which when I click on Activate button, the value in my Django database for this field changes to \'Active\' and is displayed on the HTML p
If you need only two states (active and innactive) you need a BooleanField
, so in your model you add something like this:
active = models.BooleanField(default = False)
Then, you need to create a function in your views.py to update the model in the database (I will name it ajax_change_status):
from django.http import JsonResponse
from xxx.models import Job
def ajax_change_status(request):
active = request.GET.get('active', False)
job_id = request.GET.get('job_id', False)
# first you get your Job model
job = Job.objects.get(pk=job_id)
try:
job.active = active
job.save()
return JsonResponse({"success": True})
except Exception as e:
return JsonResponse({"success": False})
return JsonResponse(data)
Then, you add the url for you ajax function in the urls.py:
url(r'^ajax/change_status/$', views.ajax_change_status, name='ajax_change_status')
and finally in you HTML, you need to call the function each time you click the button:
finally, don't forget to put the csrf tag in you HTML:
{% csrf_token %}