GrantU
GrantU

Reputation: 6555

Django check if form choice is empty

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

Answers (3)

David Ogutu
David Ogutu

Reputation: 13

There's now an exists method. This is more efficient than counting for most database backends.

Upvotes: 0

Paulo Bu
Paulo Bu

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

karthikr
karthikr

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

Related Questions