【问题标题】:Django-Tables2 with Checkbox Prefilled Value带有复选框预填充值的 Django-Tables2
【发布时间】:2020-10-13 20:11:13
【问题描述】:

我正在尝试使用 django-tables2 预渲染选中的复选框,但无法成功。

这是我的 tables.py 文件。 id 是我需要存储的字段,因为它用于更新数据库,在表单提交时将 selected 字段设置为 true。我怎样才能让checked 参数使用它并正确引用selected 字段?

class SomeTable(tables.Table):
    add = tables.CheckBoxColumn(accessor='id',checked='selected')

    class Meta:
        model = SomeModel
        template_name = "django_tables2/bootstrap.html"
        fields = ['name','add']

谢谢!

【问题讨论】:

    标签: django django-tables2


    【解决方案1】:

    您可以通过使用Table.render_foo method 来实现此目的,如果此列会覆盖呈现:

    from django_tables2.utils import AttributeDict
    
    class SomeTable(tables.Table):
        add = tables.CheckBoxColumn(empty_values=())
    
        def render_add(self, value, bound_column, record):
            default = {"type": "checkbox", "name": bound_column.name, "value": record.id}
            general = self.attrs.get("input")
            specific = self.attrs.get("td__input")
            attrs = AttributeDict(default, **(specific or general or {}))
            return mark_safe("<input %s/>" % attrs.as_html())
    
        class Meta:
            model = SomeModel
            template_name = "django_tables2/bootstrap.html"
            fields = ['name','add']
    

    【讨论】:

    • 感谢您的回复。但是我将如何为我的情况定制这个呢?我有“id”字段,因此可以在views.py中正确调用和更新它,“selected”二进制字段应该是标志,如果它被选中。
    • 当您提交此表单(例如?add=1&amp;add=3)时,您将收到每个选定项目的 add 参数的多个实例。不提交未标记的条目。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 2020-02-19
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    相关资源
    最近更新 更多