社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

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

jelly_bean • 4 年前 • 568 次点击  

我正在创建一个模板,它显示一个按钮,但仅当特定用户在模型中有一个“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
 
568 次点击  
文章 [ 1 ]  |  最新文章 4 年前
arjun
Reply   •   1 楼
arjun    4 年前

自从你 Path 模型具有 OneToOne 与…的关系 User

{% if request.user.path.path %}
    <button class="btn btn-outline-info" onclick="function()" id='button'> Initiate Index </button>
{% else %}
    No button
{% endif %}