关于问题: - 我有一个名为topics的表单字段,其中包含manytomanyfield。现在在模板中,我在字段集内的div中调用{{form.topics}}
。我想检查{{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}}是复选框列表。我希望没有复选框时({{form.topics is empty}})不显示字段集 这是通过jquery实现的。我希望像{{form.topics.empty}}这样的东西不显示 step4字段集。有没有什么好方法可以删除那个jquery。
提前致谢..
答案 0 :(得分:2)
我建议你计算变量的长度
在您的视图中forms.topics
,只需在模板中使用此变量
即可{% if not forms.topic or variable <= 1 %}
<td>Whatever you want to display</td>
{% else %}
<td> {{ forms.topic }} </td>
{% endif %}
此代码检查“forms.topic”中是否没有值,或者变量的长度(在视图中计算的)小于或等于1.打印要显示的文本。