如何获取模板标签以自动检查Django中的复选框

时间:2010-03-15 13:05:24

标签: python django templatetags

我正在使用ModelForm类为ManyToManyField生成一堆复选框,但我遇到了一个问题:默认行为会自动检查相应的框(当我编辑对象时),我可以'弄清楚如何在我自己的自定义模板标签中获取该信息。

以下是我在模特中的内容:

from myproject.interests.models import Interest


class Node(models.Model):
    interests   = models.ManyToManyField(Interest, blank=True, null=True)


class MyForm(ModelForm):

    from django.forms import CheckboxSelectMultiple, ModelMultipleChoiceField

    interests = ModelMultipleChoiceField(
        widget=CheckboxSelectMultiple(), 
        queryset=Interest.objects.all(),
        required=False
    )

    class Meta:
        model = MyModel

在我看来:

from myproject.myapp.models import MyModel,MyForm

obj = MyModel.objects.get(pk=1)
f   = MyForm(instance=obj)

return render_to_response(
    "path/to/form.html", {
        "form": f,
    },
    context_instance=RequestContext(request)
)

在我的模板中:

{{ form.interests|alignboxes:"CheckOption" }}

这是我的模板标签:

@register.filter
def alignboxes(boxes, cls):
    """
        Details on how this works can be found here:
            http://docs.djangoproject.com/en/1.1/howto/custom-template-tags/
    """

    r = ""
    i = 0
    for box in boxes.field.choices.queryset:
        r += "<label for=\"id_%s_%d\" class=\"%s\"><input type=\"checkbox\" name=\"%s\" value=\"%s\" id=\"id_%s_%d\" /> %s</label>\n" % (
            boxes.name,
            i,
            cls,
            boxes.name,
            box.id,
            boxes.name,
            i,
            box.name
        )
        i = i + 1

    return mark_safe(r)

问题是,我只是这样做,所以我可以在这些盒子周围加一些更简单的标记,所以如果有人知道如何以更简单的方式实现这一点,我会全神贯注。我很高兴知道如何检查是否应该检查一个方框。

2 个答案:

答案 0 :(得分:3)

在复选框的 input 标记中,您只需根据某些条件添加已选中的属性即可。假设你的盒子对象有属性已检查哪个值是“已选中”或空字符串“”

r += "<label for=\"id_%s_%d\" class=\"%s\"><input type=\"checkbox\" name=\"%s\" value=\"%s\" id=\"id_%s_%d\" %s /> %s</label>\n" % (
    boxes.name,
    i,
    cls,
    boxes.name,
    box.id,
    boxes.name,
    i,
    box.checked,
    box.name
)

答案 1 :(得分:0)

结果显示我要查找的值,列表中被“检查”的元素不在field中,而是form对象的一部分。我重新设计了模板标签,看起来像这样,它完全符合我的需要:

@register.filter
def alignboxes(boxes, cls):

    r = ""
    i = 0
    for box in boxes.field.choices.queryset:
        checked = "checked=checked" if i in boxes.form.initial[boxes.name] else ""
        r += "<label for=\"id_%s_%d\" class=\"%s\"><input type=\"checkbox\" name=\"%s\" value=\"%s\" id=\"id_%s_%d\" %s /> %s</label>\n" % (
            boxes.name,
            i,
            cls,
            boxes.name,
            box.pk,
            boxes.name,
            i,
            checked,
            box.name
        )
        i = i + 1

    return r

对于那些可能会遇到的人,请注意checked

中找到了上面的boxes.form.initial[boxes.name]
相关问题