我正在使用 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)
问题是,我这样做只是为了可以在这些框周围包裹一些更简单的标记,所以如果有人知道如何以更简单的方式实现这一点,我会全力以赴。我很高兴知道一种方法来访问是否应该检查一个框。