Django check if form choice is empty

假装没事ソ 提交于 2020-01-25 10:43:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!