单击Django中的按钮后,更改布尔值

时间:2018-11-07 19:07:52

标签: ajax django button boolean

我需要一些有关按钮单击和布尔值更改的帮助。

我的模特:

class Topic(models.Model):
subject = models.CharField(max_length=255)
category = models.CharField(max_length=255)
last_updated = models.DateTimeField(auto_now_add=True)
starter = models.ForeignKey(User, on_delete=models.CASCADE, related_name='topics')
slug = models.SlugField(unique=True)
isReported = models.BooleanField(default=False)
startPrice = models.IntegerField(validators=[RegexValidator(r'^\d{1,10}$')])

我想在单击按钮后将字段“ isReported”的状态从默认值“ False”更改为“ True”:

<button type="submit" class="btn btn-primary btn-block">Report</button>

我已经在google上搜索并在SO(How do I change a value in django on button click in HTML?)上找到了类似的内容,但是我对该线程中提出的概念缺乏了解。不幸的是,这是我唯一能找到的有用信息。

单击按钮后如何更改数据库中的布尔值?不必重新更改该按钮上的值。

我某处试图修改链接的代码:

views.py:

def ajax_change_status(request):
isReported = request.GET.get('isReported', False)
pk = request.GET.get('pk', False)
# first you get your Job model
job = Topic.objects.get(pk=pk)
try:
    job.isReported = isReported
    job.save()
    return JsonResponse({"success": True})
except Exception as e:
    return JsonResponse({"success": False})
return JsonResponse(data)

xxx.html:

    <form method="post" novalidate>
    {% csrf_token %}
    <button type="submit" class="btn btn-danger btn-sm" id="change" role="button">Report</button>
    </form>

<script>
     $("#change").on('click', function () {

  var pk = '{{ topic.pk }}'
  var isReported = 'True'

  $.ajax({
    url: '/ajax/change_status/',
    data: {
      'isReported': isReported
      'pk': pk
    },
    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.");
      }
    }
  });

});

我试图理解这个概念,但是(无效)它不起作用。

POST /request/xxx-xxx-xxx-5622149-3/ HTTP/1.0" 200 5472

0 个答案:

没有答案