How do I change a value in django on button click in HTML?

后端 未结 1 1456
[愿得一人]
[愿得一人] 2021-01-24 23:14

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

1条回答
  •  滥情空心
    2021-01-25 00:12

    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 %}
    

    0 讨论(0)
提交回复
热议问题