我有一个包含3个字段的PersonTag
模型的modelformset,我希望显示PersonTag.enabled
字段的复选框小部件,而不显示其他两个字段的小部件。对于每个复选框,我希望将标签设置为该模型实例的PersonTag.tag
值。我怎么能做到这一点?
models.py:
from django.db import models
class Person(models.Model):
name_person = models.TextField()
tags = models.ManyToManyField('Tag', through='PersonTag')
class Tag(models.Model):
name_tag = models.TextField()
persons_tagged = models.ManyToManyField('Person', through='PersonTag')
class PersonTag(models.Model):
person = models.ForeignKey('Person')
tag = models.ForeignKey('Tag')
enabled = models.BooleanField(default=False)
views.py:
from django.forms.widgets import HiddenInput
from django.forms.models import modelformset_factory
from django.shortcuts import render
from models import Person, PersonTag, Tag
def home(request):
# Should I use a HiddenInput here for 'tag', or is it not necessary?
ModelFormset_PersonTag = modelformset_factory(model=PersonTag,
extra=0,
fields=('enabled','tag',),
widgets=dict(tag=HiddenInput()))
# Arbitrarily choose a person for this example
person = Person.objects.all()[0]
if request.method == 'GET':
modelformset_persontag = ModelFormset_PersonTag(
queryset=PersonTag.objects.filter(person=person))
for form in modelformset_persontag.forms:
# How to reference the .tag.label value here?
form.fields['enabled'].label = form.fields['tag'].widget.???
return render(request=request,
template_name='home.html',
dictionary=dict(
modelformset_persontag=modelformset_persontag))
home.html的:
<html>
<body>
<form method="post" action=""> {% csrf_token %}
{{ modelformset_persontag.management_form }}
{% for form_persontag in modelformset_persontag %}
{{ form_persontag }}
{% endfor %}
<input type="submit" value="Submit" />
</form>
</body>
</html>
答案 0 :(得分:0)
我找到了一个我喜欢的解决方案:
form.fields['enabled'].label = form.instance.tag.name_tag
不需要带有PersonTag.tag
窗口小部件的HiddenValue
字段(尽管可以根据需要使用它):
ModelFormset_PersonTag = modelformset_factory(model=PersonTag,
extra=0,
fields=('enabled',))
虽然不再需要,但我很好奇如何获得form.fields['tag'].widget.???
的价值。