【问题标题】:How can I link an input to an object's attribute and update that attribute as you click on it?如何将输入链接到对象的属性并在单击时更新该属性?
【发布时间】:2020-10-27 17:58:07
【问题描述】:

鉴于这些模型、视图和模板文件:

models.py

class Item(models.Model):
    class Included(models.IntegerChoices):
        YES = 1
        NO = 0

    included = models.IntegerField(choices=Included.choices, default=Included.YES)
    name = models.CharField()

views.py

def index(request):
    items = Item.objects.all()

    context = {
                'items':item
                }

    return render(request, template.html, context(

template.html

{% for item in items %}
    {{ item.name }}
    <input type="checkbox">
{% endfor %}

我该怎么做才能使复选框反映是否包含Item

我如何通过勾选复选框来更改它是否包含?

一般来说,如何将输入链接到对象的属性并在单击时更新该属性?

我认为在这里使用forms 是不可行的,因为它只会更改一个字段。另外,如果可能,请实时进行。除非您刷新页面,否则表单不会更新页面,有什么想法吗?

【问题讨论】:

    标签: python python-3.x django django-templates


    【解决方案1】:

    您可以在复选框中添加onChange 处理程序,并在单击复选框时提交POST 请求。

    document.querySelector('#cbox').addEventListener('change', function (e) {
      var item_id = this.getAttribute('data-item-id')
      var checked = this.checked
      
      console.log('Item ID:', item_id)
      console.log('Checkbox is checked?', checked)
      
      //fetch('url here', {
      //  method: 'POST',
      //  body: {item_id: item_id, checked: checked}
      //});
    })
    &lt;input id="cbox" data-item-id="{{ item.id }}" type="checkbox" /&gt;

    然后您的视图将如下所示:

    from django.http import JsonResponse
    def handleCheckbox(request):
        if request.POST:
            item_id = request.POST['item_id']
            checked = 1 if request.POST['checked'] == True else 0
            
            item = Item.objects.get(id=item_id)
            item.included = checked
            item.save()
    
            return JsonResponse({'message': 'Success'})
    

    【讨论】:

      猜你喜欢
      • 2016-07-18
      • 2016-01-03
      • 2018-07-09
      • 2015-02-04
      • 1970-01-01
      • 2023-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多