问题
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
回答1:
You can do:
{% if form.templates.field.choices.queryset.all|length %}
<div class="control-group">
<div class="controls">
{{ form.templates }}
</div>
回答2:
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!
回答3:
There's now an exists
method. This is more efficient than counting for most database backends.
来源:https://stackoverflow.com/questions/16640448/django-check-if-form-choice-is-empty