django - Quering date and time field and render in template -
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)
template is
{{ reports.created_date_time|date:"j m y g:i a" }}
fetching created_date_time database , convert format 20 jan2011 @ 2:26pm
display in template.
to query created_date_time database , display template.i not getting error in code,i think logic having problem not happening.
reports
variable accessed in template single report object, list of report object.
to access first item in list in template, use following syntax:
{{ reports.0.created_date_time|date:"j m y g:i a" }}
now, easiest way print date in format you've mentioned is:
{{ reports.0.created_date_time|date:"j m y" }} @ {{ reports.0.created_date_time|date:"g:i a" }}
but, mind, better way create custom template filter, print desired format.
your_app/templatetags/format_dates.py
from django.utils.dateformat import format 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 @ %s" % (format(value, 'j m y'), format(value, 'g:i a')) except attributeerror: return u''
and in template:
{% load format_dates %} ... {{ reports.0.created_date_time|format_date }}
Comments
Post a Comment