1

ModelFormクラスを使用してManyToManyFieldのチェックボックスを生成していますが、1つの問題が発生しました。デフォルトの動作では、適切なボックスが自動的にチェックされますが(オブジェクトを編集している場合)、理解できません。私自身のカスタムテンプレートタグでその情報を取得する方法。

これが私のモデルにあるものです:

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)

重要なのは、私はこれを行っているだけなので、これらのボックスの周りにいくつかの単純なマークアップをラップできるので、誰かがそれをより簡単な方法で実現する方法を知っていれば、私はすべての耳です。ただし、チェックボックスをオンにする必要があるかどうかにアクセスする方法を知っていれば幸いです。

4

2 に答える 2

3

チェックボックスの入力タグでは、条件に基づいて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
)
于 2010-03-15T14:53:40.473 に答える
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]

于 2010-03-16T04:17:19.907 に答える