0

视图.py

def new_report(request):
    user = request.user
    reports = Report.objects.filter(user=user)
    today = datetime.datetime.today()

    reports_today = reports.filter(created_date_time__year=today.year, created_date_time__month=today.month, created_date_time__day=today.day)
    num_today = len(reports_today) + 1
    num_today = str(num_today).zfill(3)
    reportform = ReportForm()
    if request.method == 'POST':
        reportform = ReportForm(request.POST)
        if reportform.is_valid():
            report = reportform.save(commit=False)
            report.user = user
            report.created_date_time = today
    return render(request, 'incident/new_report.html',
                  {
                   'newreport_menu': True,
                   'reports': reports,
                   'reportform':ReportForm,
                 })

模型.py

class Report(models.Model):
    user = models.ForeignKey(User, null=False)
    incident_number = models.CharField('Incident Number', max_length=100)
    device_id = models.CharField('Device Id', max_length=100)
    app_uuid = models.CharField('Unique App Id', max_length=100)
    created_date_time = models.DateTimeField('Created',auto_now=True)

模板是

{{ reports.created_date_time|date:"j M Y g:i A" }}

从数据库中获取 created_date_time 并转换为此格式20 Jan2011 at 2:26PM以显示在模板中。

从数据库中查询 created_date_time 并显示到模板中。我在代码中没有收到任何错误,我认为某些逻辑有问题,所以它没有发生。

4

1 回答 1

0

reports变量在模板中访问,因为它是单个 Report 对象,但它是 Report 对象的列表。

要访问模板列表中的第一项,请使用以下语法:

{{ reports.0.created_date_time|date:"j M Y g:i A" }}

现在,以您提到的格式打印日期的最简单方法是:

{{ reports.0.created_date_time|date:"j M Y" }} at {{ reports.0.created_date_time|date:"g:i A" }}

但是,在我看来,更好的方法是创建自定义模板过滤器,它将打印所需的格式。

your_app/templatetags/format_dates.py

from django.utils.dateformat import format
from django.template.base import Library

register = Library()

@register.filter(expects_localtime=True, is_safe=False)
def format_date(value):
    if not value:
        return u''
    try:
        return u"%s at %s" % (format(value, 'j M Y'), format(value, 'g:i A'))
    except AttributeError:
        return u''

然后在模板中:

{% load format_dates %}

...

{{ reports.0.created_date_time|format_date }}
于 2013-05-04T14:22:56.827 回答