Django检查表单选择是否为空

Gra*_*ntU 0 django django-templates

在模板中,如何检查ModelChoiceField是否为

这是我的表格:

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)
Run Code Online (Sandbox Code Playgroud)

然后在我的意见我想显示下拉如果查询集为空,这样的事情...

{% if not form.templates%}
<div class="control-group">
  <div class="controls">
    {{ form.templates }}
  </div>
etc
Run Code Online (Sandbox Code Playgroud)

kar*_*ikr 6

你可以做:

{% if form.templates.field.choices.queryset.all|length %}

<div class="control-group">
  <div class="controls">
    {{ form.templates }}
  </div>
Run Code Online (Sandbox Code Playgroud)