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

后端 未结 1 1453
[愿得一人]
[愿得一人] 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:

    <script>
        $("#button_id").on('click', function () {
          var username = $(this).val();
          var active = <true> // or false, you have to set it
          var active = <id> // you have to set it
          $.ajax({
            url: '/ajax/validate_username/',
            data: {
              'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(),
              'active': active
              'job_id': username
            },
            dataType: 'json',
            success: function (data) {
              if (data.success) {
                alert("ajax call success.");
                // here you update the HTML to change the active to innactive
              }else{
                alert("ajax call not success.");
              }
            }
          });
    
        });
      </script>
    

    finally, don't forget to put the csrf tag in you HTML:

    {% csrf_token %}
    
    0 讨论(0)
提交回复
热议问题