Django检查表单选项是否为空
问题描述:
在模板中,如何检查 ModelChoiceField 是否为空?
In a template how is it possible to check if a ModelChoiceField is empty?
这是我的形式:
class BatchForm(forms.ModelForm):
def __init__(self, user=None, *args, **kwargs):
super(BatchForm, self).__init__(*args, **kwargs)
this_templates = Template.objects.for_user(user)
self.fields["templates"] = forms.ModelChoiceField(queryset=this_templates, required=False, empty_label=None)
然后在我的视图我想要不显示下拉列表,如果查询器是空的这样的...
Then in my views I want to not show the drop down if the queryset is empty something like this...
{% if not form.templates%}
<div class="control-group">
<div class="controls">
{{ form.templates }}
</div>
etc
答
你可以做: p>
You can do:
{% if form.templates.field.choices.queryset.all|length %}
<div class="control-group">
<div class="controls">
{{ form.templates }}
</div>