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

如何获取Django按钮点击时间并在指定模板展示

实现方案

1. 扩展数据库模型

首先在发票模型(示例命名为Factura)中新增字段,用于存储按钮点击的验证时间:

# models.py
from django.db import models
from django.utils import timezone

class Factura(models.Model):
    # 保留原有字段...
    fecha_validacion = models.DateTimeField(
        null=True, blank=True, 
        verbose_name="Fecha de validación"
    )
    # 其他字段...

执行数据库迁移命令:

python manage.py makemigrations
python manage.py migrate

2. 修改状态更新视图

在cambiar_estado_factura视图中,除了修改发票状态,同时写入当前时间到新增字段:

# views.py
from django.shortcuts import get_object_or_404, redirect
from django.utils import timezone
from .models import Factura

def cambiar_estado_factura(request, id_factura, nuevo_estado):
    factura = get_object_or_404(Factura, id_factura=id_factura)
    # 更新发票状态
    factura.id_estado_id = nuevo_estado
    # 记录点击按钮的当前时间
    factura.fecha_validacion = timezone.now()
    factura.save()
    # 重定向到已验证发票列表页
    return redirect('v_facturasvalidadas')

3. 更新已验证发票页面的表格显示

将facturasvalidadas.html中的占位符替换为模型字段,并添加时间格式化:

<!-- 修改表格中对应<td>标签 -->
<td>{{ factura.fecha_validacion|date:"d/m/Y H:i:s" }}</td>

这里使用Django内置的date过滤器格式化时间,可根据需求调整格式字符串(比如"Y-m-d H:i")。

4. (可选)AJAX方式优化交互(非必须)

如果需要避免页面直接跳转的刷新感,可将<a>标签改为按钮,用JavaScript发送AJAX请求:

<!-- d_facturaspendientes.html 按钮修改 -->
<div class="d-flex justify-content-center" style="margin: 1em;">
    <button data-factura-id="{{ factura.id_factura }}" data-estado="2" class="btn btn-success btn-lg mx-2" style="width: 150px;">Aceptar</button>
    <button data-factura-id="{{ factura.id_factura }}" data-estado="3" class="btn btn-danger btn-lg mx-2" style="width: 150px;">Rechazar</button>
</div>

<script>
document.querySelectorAll('.btn-success, .btn-danger').forEach(btn => {
    btn.addEventListener('click', function() {
        const facturaId = this.dataset.facturaId;
        const estado = this.dataset.estado;
        fetch(`{% url 'cambiar_estado_factura' 0 0 %}`.replace('0', facturaId).replace('0', estado), {
            method: 'POST',
            headers: {
                'X-CSRFToken': '{{ csrf_token }}',
                'Content-Type': 'application/json'
            }
        }).then(res => {
            if(res.ok) window.location.href = '{% url 'v_facturasvalidadas' %}';
        });
    });
});
</script>

同时确保视图支持POST请求(上述视图已兼容GET/POST)。

内容的提问来源于stack exchange,提问作者Mario Gómez Peña

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 22:37:05