You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django模板中实现if条件为真时自动跳转页面?

Django模板中根据模型属性实现自动页面跳转

我有一个展示数据库信息的Django模板页面,需求是:当模型的comm_time_compare属性返回True时,页面自动跳转到指定页面,无需用户点击操作。之前尝试用a标签实现,但需要手动点击,不符合要求。

相关代码

Communications.html模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    {% load bootstrap5 %}
    {% bootstrap_css %}
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">
 <style>
  label{
    font-size: 18px;
  }
 </style>
</head>
<body>

    <table id="tblToExcl" class="table table-striped table-bordered table-sm">  
        <thead class="thead-dark">  
        <tr>  
         
          <th>Day</th>  
            <th>From</th>  
            <th>To</th>  
            <th>Name Lecturer</th>  
            <th>Lesson</th>  
            <th>Lab</th>
          
        </tr>  
        </thead>  
        <tbody>  
    {% for table in tables %}  
        <tr>  
           
            <td>{{ table.day }}</td>  
            <td>{{ table.strt_lec }}</td>  
            <td>{{ table.end_lec }}</td>  
            <td>{{ table.name_lecurer }}</td>
            <td>{{ table.name_lesson }}</td>  
            <td>{{ table.lab }}</td>   
           
          {% if table.comm_time_compare%}
             
             <p>time is equal</p>
            

          {% else %}   
             <p> time is not equal</p>

          {% endif %}   
        </tr>  
    {% endfor %}  
        </tbody>  
    
    </table>  
    

</body>
</html>

models.py模型代码

class Communications(models.Model):
    day = models.CharField(max_length=20)
    strt_lec = models.CharField(max_length=20)
    end_lec = models.CharField(max_length=20)
    name_lecurer = models.CharField(max_length=40, choices=LECTURER_NAME_Comm)
    name_lesson = models.CharField(max_length=70, choices=LESSONS_Comm)
    lab = models.CharField(max_length=20, choices=LAB_NAMES_Comm)

    @property
    def comm_time_compare(self):
        current_time = time.strftime("%I:%M")
        if current_time == self.strt_lec:
            return True
        else:
            return False

urls.py路由代码

from django.urls import path
from . import views
from django.views.generic import TemplateView

urlpatterns = [
    path('members/', views.members, name='members'),
    path('', views.index, name='index'),
    path('Communications', views.show_Communications, name='Communications'),
    path('table', views.Communications_table, name='table'),
]

解决方案

方案1:视图层直接判断跳转(推荐)

在视图函数中提前检查是否存在满足条件的记录,若存在则直接重定向,无需渲染页面,效率更高。修改views.py中的show_Communications函数:

from django.shortcuts import render, redirect

def show_Communications(request):
    tables = Communications.objects.all()
    # 遍历检查是否有符合条件的记录
    for table in tables:
        if table.comm_time_compare:
            # 替换为你需要跳转的页面路由name,比如'index'或'table'
            return redirect('index')
    # 无符合条件的记录,正常渲染页面
    return render(request, 'Communications.html', {'tables': tables})

方案2:模板中通过JavaScript实现跳转

如果需要先渲染页面再触发跳转,可在模板的</body>标签前添加判断逻辑,通过JS实现自动跳转:

{% for table in tables %}
    {% if table.comm_time_compare %}
        <script>
            // 替换为目标页面的路由name生成的URL
            window.location.href = "{% url 'index' %}";
        </script>
        {% break %} <!-- 找到第一个符合条件的记录后停止,避免多次触发跳转 -->
    {% endif %}
{% endfor %}

注意事项

  • 确保strt_lec字段存储的时间格式与comm_time_compare中time.strftime("%I:%M")的格式完全一致(12小时制,带前导零,如09:30),否则时间比对会失效。
  • 若需要仅在特定日期同时满足时跳转,可在comm_time_compare属性中增加日期判断逻辑。

内容的提问来源于stack exchange,提问作者Rasool ALmusawie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 13:22:25