有没有办法通过Django模板在if条件中使用模型字段?
我正在创建一个显示按钮的模板,但仅当特定用户在模型中具有“路径”字段时才显示。如何在if条件中使用model属性 这是我当前的代码: models.py:有没有办法通过Django模板在if条件中使用模型字段?,django,python-3.x,Django,Python 3.x,我正在创建一个显示按钮的模板,但仅当特定用户在模型中具有“路径”字段时才显示。如何在if条件中使用model属性 这是我当前的代码: models.py: from django.db import models from django.contrib.auth.models import User class Path(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) pa
from django.db import models
from django.contrib.auth.models import User
class Path(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
path = models.CharField(max_length = 255, blank=False, null=False) #Will not accept empty string or None
created_date = models.DateTimeField(auto_now = True)
def __str__(self):
return f"{self.user.username}"
template.html:
{% if request.user.path.path %}
<button class="btn btn-outline-info" onclick="function()" id='button'> Initiate Index </button>
{% else %}
<button class="btn btn-outline-info" onclick = "function()" id = 'abort_button'> Initiate Index </button>
{% endif %}
{% block javascript %}
<script type="text/javascript">
$(document).ready(function() {
$("#button").click(function() { #If path is available
alert('Thank you...');
});
$("#abort_button").click(function() { #If path is not available
alert('Please insert path');
});
});
</script>
{% endblock %}
{%if request.user.path.path%}
启动索引
{%else%}
启动索引
{%endif%}
template.html中的jquery:
{% if request.user.path.path %}
<button class="btn btn-outline-info" onclick="function()" id='button'> Initiate Index </button>
{% else %}
<button class="btn btn-outline-info" onclick = "function()" id = 'abort_button'> Initiate Index </button>
{% endif %}
{% block javascript %}
<script type="text/javascript">
$(document).ready(function() {
$("#button").click(function() { #If path is available
alert('Thank you...');
});
$("#abort_button").click(function() { #If path is not available
alert('Please insert path');
});
});
</script>
{% endblock %}
{%block javascript%}
$(文档).ready(函数(){
$(“#按钮”)。如果路径可用,请单击(函数(){#)
警惕(‘谢谢……’);
});
$(“#中止#按钮”)。如果路径不可用,请单击(函数(){#
警报(“请插入路径”);
});
});
{%endblock%}
提前谢谢。由于您的
路径
模型与用户
模型有OneToOne
关系,因此您可以检查当前登录的用户在模板中是否有路径字段
{% if request.user.path.path %}
<button class="btn btn-outline-info" onclick="function()" id='button'> Initiate Index </button>
{% else %}
No button
{% endif %}
{%if request.user.path.path%}
启动索引
{%else%}
没有按钮
{%endif%}
由于路径字段中添加了blank=False、null=False,因此每个路径对象都将有一个非空的路径字段。对吧?对。但我的意图是显示一个提醒“谢谢”的按钮(如果有的话)。或者,如果该路径在数据库中不可用,则发出警告“请添加路径”。我再次更新了问题,请看一下。这次,它只显示{%else%}部分,但else条件后面的按钮不起作用。我已经更新了这个问题。请再看看。谢谢。@jelly\u bean你为什么要根据你的模型做{%if request.user.imagepath.image\u path%}
只要做{%if request.user.path.path%}
。我的错误。if/else条件有效,但按钮没有响应。我修复了它!非常感谢。jQuery代码就是问题所在。