Django检查表单选项是否为空 [英] Django check if form choice is empty
本文介绍了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>
这篇关于Django检查表单选项是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文