Reputation: 6555
In a template how is it possible to check if a ModelChoiceField is empty?
This is my form:
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
Upvotes: 0
Views: 2271
Reputation: 13
There's now an exists
method. This is more efficient than counting for most database backends.
Upvotes: 0
Reputation: 29804
Just test the count
of the queryset in your form field:
{% if form.templates.queryset.count %}
<div class="control-group">
<div class="controls">
{{ form.templates }}
</div>
</div>
{%endif%}
Hope it helps!
Upvotes: 2
Reputation: 99660
You can do:
{% if form.templates.field.choices.queryset.all|length %}
<div class="control-group">
<div class="controls">
{{ form.templates }}
</div>
Upvotes: 5