關於問題: - 我有一個名爲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。
在此先感謝..
請不要縮進你的文本段落 – Marcin 2012-02-09 11:00:27
你在尋找{%if form.topics%}構造嗎? – akonsu 2012-02-09 12:17:08
嗯,我只是尋找計算form.topics或len的長度(f.fields ['topics']。queryset) – 2012-02-10 06:23:56