我在django中有一个html文件。 如果满足特定条件,我想显示一个按钮,否则根本不显示它。
这是相关代码:
urls.py
:
url(r'^hellos/(?P<id>.*)/$', hello, name = hello),
views.py
:
def hello(request, id):
....
try:
a = ItemHello.objects.get(idx = int(id))
except ObjectDoesNotExist:
raise Http404
alreadyfilled = False
if a.check_alreadyfilled():
print alreadyfilled
alreadyfilled = True
models.py
:
class ItemHello(models.Model):
idx= models.IntegerField(primary_key = True)
answered = models.DateField(null = True, blank = True)
...
def check_alreadyfilled(self):
if self.answered:
return True
else:
return False
hello.html
:
<tr>
<td>{% if not alreadyfilled %}<input type="button" value="Save" onclick="doSubmit();" />{% endif %}</td>
</tr>
然而,这不起作用。
已填充的获取正确的值。我检查了alreadyfilled
中views.py
的打印件,它正确地提供了true
和false
,但是对于某些读取器,hello.html总是声称{% if not alreadyfilled %}
是真的并且显示按钮。
有什么问题?
答案 0 :(得分:1)
您需要在模板的上下文中发送alreadyfilled
参数。
由于您没有发送此变量,因此模板始终显示按钮。
您可以创建context
dict并在渲染模板时传递context
。然后,这会将变量alreadyfilled
传递给模板。
def hello(request, id):
....
try:
a = ItemHello.objects.get(idx = int(id))
except ObjectDoesNotExist:
raise Http404
alreadyfilled = False
if a.check_alreadyfilled():
print alreadyfilled
alreadyfilled = True
...
context = {'alreadyfilled': alreadyfilled} # pass the parameter in the context
return render(request, 'template_name.html', context)