如何在模板中呈现ChoiceField值?

时间:2017-09-19 10:29:33

标签: django

我在模板中获取ChoiceField值时遇到问题。这是表单定义(单个无线电选择字段,描述产品是否“花哨”):

CHOICES = (
    (True, "Yes"),
    (False, "No"),
)

class ProductCreateForm(forms.ModelForm):
    fancy = forms.ChoiceField(
        required=True,
        label="Is this product fancy?",
        widget=forms.RadioSelect(),
        choices=CHOICES,
        )

当我在shell中执行此操作时,我得到None

from django.template import Template, Context
p = Product.objects.first()
form = ProductCreateForm(instance=p)
t = Template("{{ form.fancy.value }}")
c = Context({"form":form})
p.fancy is False
>>> True
print(t.render(c))
>>> None

即使我尝试只渲染字段,也没有选择任何单选按钮:

t = Template("{{ form.fancy }}")
c = Context({"form":form})
print(t.render(c))
>>> #showing only the two input tags for brevity
>>> <input type="radio" name="basic" value="True" required id="id_basic_0" />
>>> <input type="radio" name="basic" value="False" required id="id_basic_1" />
  1. {{ form.field.value }}是从表单中获取ChoiceField值的正确方法吗?
  2. 为什么不在checked上使用正确的{{ form.fancy.1 }}属性渲染无线电?
  3. 我正在使用django 1.11。

    编辑:这是一个示例Product类,因此您可以复制shell中的所有内容:

    class Product(models.Model):
        fancy = models.BooleanField(default=False)
    

1 个答案:

答案 0 :(得分:0)

您覆盖ModelForm将添加的内容:ModelChoiceField。与普通forms.ChoiceField的区别在于,选择字段从绑定的模型实例中获取initial值。

如果要覆盖窗口小部件,则覆盖窗口小部件(使用auth&#39的用户模型作为示例):

from django import forms

from django.contrib.auth.models import User

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['is_active', 'is_superuser']
        widgets = {
            'is_active': forms.RadioSelect(choices=((False, 'False'), (True, 'True'))),
        }

>>> str(f['is_active'])  # reformatted
<ul id="id_is_active">
    <li>
        <label for="id_is_active_0">
            <input type="radio" name="is_active" value="False" id="id_is_active_0" />
                False</label>

    </li>
    <li>
        <label for="id_is_active_1">
            <input type="radio" name="is_active" value="True" id="id_is_active_1" checked />
                True</label>
    </li>
 </ul>

有关使用BoundField的更多信息:

>>> u = User.objects.get(id=3)
>>> u.is_active
True
>>> u.is_superuser
False
>>> f = UserForm(instance=u)
>>> f['is_superuser'].value()
False
>>> str(f['is_superuser'])
'<input type="checkbox" name="is_superuser" id="id_is_superuser" />'
>>> str(f['is_active'])
'<ul id="id_is_active">\n    <li><label for="id_is_active_0"><input type="radio" name="is_active" value="False" id="id_is_active_0" />\n Nee</label>\n\n</li>\n    <li><label for="id_is_active_1"><input type="radio" name="is_active" value="True" id="id_is_active_1" checked />\n Ja</label>\n\n</li>\n</ul>'
>>> f['is_active'].value()
True
相关问题