2012-02-09 26 views
0

關於問題: - 我有一個名爲topics的表單域,它是manytomanyfield。現在在模板中,我打電話給{{form.topics}}在一個fieldset中的div。我想檢查{{form.topics}}是否爲空,或者它的長度爲< = 1,在這種情況下,我不想顯示{{form.topics}}的字段集這裏是我的代碼。我正在使用jquery解決這個問題。檢查模板中的表單域是否爲空

forms.py 
# Showing only that field to keep code short 
    class VisitSetupForm(Form): 
    topics = ModelMultipleChoiceField(
        queryset=Topic.objects.filter(reporting=False), 
        widget=CheckboxSelectMultiple, 
        required=False 
       ) 

    Views.py 
    def setup(request): 
     if request.user.is_superuser: 
      form_class = AdminVisitSetupForm 
      all_topics = True 
     else: 
      form_class = VisitSetupForm 
      all_topics = False 

     f = form_class(request, data=request.POST or None) 
     if request.method == "POST": 
      if f.is_valid(): 
       ......so on .... 
       if request.user.is_superuser: 
        topics = cd['topics'] 
       else: 
        topics = set(list(interview.topics.all()) + list(cd['topics'])) 
      next_url = "/visit/confirmation/%s/%s/?next=%s" % (patient.user.id, interview.id, url) 
      return HttpResponseRedirect(next_url) 
    if not all_topics: 

     user = get_user(request) 
     # checking here if the topics exists for other user 
     f.fields['topics'].queryset = user.organization.topics 
     f.fields['interview'].queryset = user.organization.interviews 

     data['form'] = f 
    return render_to_response('visit/setup.html', data, context_instance=RequestContext(request)) 

    .html 
    # calling in html 
    <fieldset class="step4"> 
      <legend>Step 4 - Topic selection</legend> 
      <p>Check off any additional topics you want to add to the interview. If you want to 
      remove a topic from an interview, uncheck it.</p> 
      <div>{{ form.topics }}</div> 
     </fieldset> 
     <script> 
      if($(".step4 input:checkbox").length <= 0) 
      { 
       $(".step4").hide(); 
      } 
     </script> 

{{form.topics}}是要checkboxes.I的名單時,有沒有複選框({{form.topics爲空}})不顯示這是通過jquery.I實現字段集 想要{{form.topics.empty}}之類的東西不要顯示 step4 fieldset。有沒有什麼好的方法,以便我可以刪除該jquery。

在此先感謝..

+0

請不要縮進你的文本段落 – Marcin 2012-02-09 11:00:27

+0

你在尋找{%if form.topics%}構造嗎? – akonsu 2012-02-09 12:17:08

+0

嗯,我只是尋找計算form.topics或len的長度(f.fields ['topics']。queryset) – 2012-02-10 06:23:56

回答

1

我建議你來計算變量

forms.topics的長度

在你看來

,只是在你的模板中使用這個變量as

{% if not forms.topic or variable <= 1 %} 
    <td>Whatever you want to display</td> 
{% else %} 
    <td> {{ forms.topic }} </td> 
{% endif %} 

此代碼檢查是否沒有「forms.topic」中的值或變量的長度(您在視圖中計算的值)小於或等於1.打印要顯示的文本。

+0

這就是問題是我正在使用variable = len(f.fields ['topics']。 queryset)我也使用了count,它顯示管理器也沒有屬性len()。計算完該字段的長度後,我可以在模板中使用它。我如何計算長度?我在做什麼錯誤? – 2012-02-10 06:26:31

+0

@the_game:我想你應該首先打開python shell並查看f.fields ['topics']。queryset正在產生什麼,它是否能夠爲你獲取某個值,它可能是一個元組,列表或字符串。請首先確認。 – Prateek 2012-02-14 12:15:33