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

发布于 2024-08-25 13:17:39 字数 1739 浏览 6 评论 0原文

我正在使用 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)

问题是,我这样做只是为了在这些框周围包装一些更简单的标记,所以如果有人知道如何以更简单的方式实现这一点,我洗耳恭听。我很高兴知道一种方法来访问是否应该选中某个框。

I'm using a ModelForm class to generate a bunch of checkboxes for a ManyToManyField but I've run into one problem: while the default behaviour automatically checks the appropriate boxes (when I'm editing an object), I can't figure out how to get that information in my own custom templatetag.

Here's what I've got in my model:

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

And in my view:

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)
)

And in my template:

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

And here's my templatetag:

@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)

The thing is, I'm only doing this so I can wrap some simpler markup around these boxes, so if someone knows how to make that happen in an easier way, I'm all ears. I'd be happy with knowing a way to access whether or not a box should be checked though.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

墨小墨 2024-09-01 13:17:39

在复选框的 input 标记中,您可以根据某些条件添加 checked 属性。假设您的盒子对象具有属性checked,其值为“checked”或空字符串“”

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
)

In your input tag for the checkbox, you can just add the checked attribute based on some condition. Say your box object has property checked which value is either "checked" or empty string ""

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
)
漫雪独思 2024-09-01 13:17:39

事实证明,我正在寻找的值,列表中“检查”的元素不在 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 中找到的[盒子名称]

Turns out the value I was looking for, the elements in the list that were "checked" isn't in the field, but rather part of the form object. I re-worked the template tag to look like this and it does exactly what I need:

@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

For those who might come after, note that the checked value above was found in boxes.form.initial[boxes.name]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文