查询日期和时间字段并在模板中呈现

时间:2013-05-04 13:26:38

标签: django django-models django-views

views.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,
                 })

models.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并显示到模板中。我没有在代码中收到任何错误,我认为某些逻辑有问题所以它没有发生。

1 个答案:

答案 0 :(得分: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" }}

但是,在我看来,更好的方法是创建custom template filter,这将打印所需的格式。

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 }}