Py学习  »  Django

是否可以通过Django模板在if条件中使用模型字段?

jelly_bean • 4 年前 • 571 次点击  

我正在创建一个模板,它显示一个按钮,但仅当特定用户在模型中有一个“path”字段时。如何在if条件中使用model属性?

型号.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)
    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}"

模板.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 %}

提前谢谢你。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54050
 
571 次点击  
文章 [ 1 ]  |  最新文章 4 年前