Render date for yesterday with a link - python

I have a workspace where users can add note, they can pick a date
I am trying to create 2 links, one for yesterday, one for tomorrow.
Right now I am using a calendar and it is fine, but I would like to create 2 quick links that send them to the note for yesterday.
So i have a code like that :
def WorkspaceYesterday(request):
yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%m%d%y')
But i dont know how to render it in my template with a link.
Thank you

# you just need to render the context 'yesterday' to your template from your function
from django.shortcuts import render
def WorkspaceYesterday(request):
yesterday = datetime.now() - timedelta(days=1)
yesterday = yesterday.strftime('%m%d%y')
render(request, 'index.html', {'yesterday': yesterday})
# In your template index.html
<p>{{ yesterday }}</p>

Related

Save Datetime in variable to reflect in HTML Django/python

I need to know how to save the date when a function was triggered. My function triggers a logic to create a report with calculations and new data every hour. My idea was to create a function that save the date this way:
def last_modify(request):
x = []
last_mod = str(datetime.now().strftime("%d/%m %H:%M"))
context = {
'date': last_mod
}
x.append(context)
render(request, 'news-dashboard.html', context)
Not sure if I'm on the right path, and if I have to reflect it in the html template Last date modified: {{ date }} this is for the users to know when was the report last updated.
Thanks for your time.

Generating a date relative to another date in Django template

I have a date in my template context, and I want to display that date plus 7 days in the rendered output.
Something like this (which does not exist):
{{some_date|plus_days:7}}
How can I do this in a Django template without writing any Python code?
You can create your own template tag:
import datetime
from django import template
register = template.Library()
#register.filter
def plus_days(value, days):
return value + datetime.timedelta(days=days)
This cannot be done in Django templates as of this writing without writing a custom template tag in Python.

Django querying on range of days with timezone.now and __range broken?

I am running Django 1.4.3 and Python 2.7, with a PostgreSQL database (9.2.2). I have a model with a "last_view" field that is a timestamp of when a record is last viewed by a user. On my front page I want to display the ten most viewed items within the last week, so in my ListView I tried using this for my queryset:
startdate = timezone.now() - datetime.timedelta(days=7)
enddate = timezone.now()
urlpatterns = patterns('',
url(r'^$',
ListView.as_view(
queryset=Tag.objects.filter(last_view__range=([startdate, enddate])).order_by('-views')[:10],
context_object_name='most_viewed_list',
template_name='tags/index.html'),
name='index'),
This works when I first load the page. If I click any of the records and "view" them, the last_view attribute is updated in the database--but if I then reload the page, this item disappears from the "Recently Viewed" list (formed by the queryset described above).
I thought the problem was related to this post, where it seems like the "enddate" of timezone.now() is limited by when I start my server process. So when I click on a link after the server is running, the "current time" is in the future compared to "now()" and outside of the range (that is why the record I click disappears on a page reload). However, if I change things to just now as in the post mentioned above, I get an error on page load:
startdate = timezone.now - datetime.timedelta(days=7)
enddate = timezone.now
unsupported operand type(s) for -: 'function' and 'datetime.timedelta'
So I cannot create my startdate variable. I can get this to work by changing my queryset from _range to _gte, but it seems like that will break over time if now() is really timestamped to when the server process starts instead of "current time."
queryset=Tag.objects.filter(last_view__gte=(timezone.now() - datetime.timedelta(days=7)).order_by('-views')[:10]
The Django Tutorial on testing does show the use of now in making queries over dates, however they do not show how to subtract days from now or use it with timedelta or a date range...
Can someone please explain how to take a time difference from the actual, current time, i.e. using now instead of now()? I would also like to better understand the limitations of using now() versus now. I cannot find great documentation on this, since all examples I can find with timedelta() refer to timezone.now() or datetime.now(), which works (just not the way I want it to).
Thanks!
Subclass ListView and override the get_queryset method. By calculating the startdate and enddate inside the get_queryset method, timezone.now() will be the time when the request was made, not when the urls.py was initially loaded.
class TagListView(ListView):
def get_queryset(self):
startdate = timezone.now() - datetime.timedelta(days=7)
enddate = timezone.now()
return Tag.objects.filter(last_view__range=[startdate, enddate]).order_by('-views')[:10]
context_object_name='most_viewed_list'
template_name='tags/index.html'
urlpatterns = patterns('',
url(r'^$', TagListView.as_view(), name='index'),
)

print page generation time

how would I print the time it took to render a page to the bottom of my site in django? i'm not sure of the application flow of django, so I don't know how this would work.
You might be interested in django-debug-toolbar, which includes a request timer and lots of other useful info for debugging things like this.
At the beginning of your view handler, save the current date/time in a variable say time_start and pass that to the template context which renders the page.
Then define a custom template filter that will create timedelta based on datetime.now() value and the original datetime passed in as a parameter like so:
from datetime import datetime
from django import template
register = template.Library()
#register.filter
def get_elapsed(time_start):
return str(datetime.now() - time_start)
Then in your template, simply display:
...
{{ time_start|get_elapsed }}
...

How do I display current time using Python + Django?

I am learning how to use Python and Django to produce a small webapp that prints out the current time. I am using this with the Google App Engine.
Right now it's only displaying a blank page, but I want it to display the current time. I also want to map the function to the home page.. not /time/.
from django.http import HttpResponse
from django.conf.urls.defaults import *
import datetime
# returns current time in html
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
def main():
# maps url to current_datetime func
urlpatterns = patterns('',
(r'^time/$', current_datetime),
)
if __name__ == '__main__':
main()
Maybe this documentation is useful to you: Time Zones
Formatting time in a view
You can get the current time using:
import datetime
now = datetime.datetime.now()
or
to get time depending on timezone:
import datetime
from django.utils.timezone import utc
now = datetime.datetime.utcnow().replace(tzinfo=utc)
to format the time you can do:
import datetime
now = datetime.datetime.now().strftime('%H:%M:%S') # Time like '23:12:05'
Formatting time in a template
You can send a datetime to the template, let's supose you send a variable called myDate to the template from the view. You could do like this to format this datetime:
{{ myDate | date:"D d M Y"}} # Format Wed 09 Jan 2008
{{ myDate | date:"SHORT_DATE_FORMAT"}} # Format 09/01/2008
{{ myDate | date:"d/m/Y"}} # Format 09/01/2008
Check the Template filter date
I hope this is useful to you
Use the now template tag. For example:
{% now "jS F Y H:i" %}
but you'll need to send your string through template engine before sending the response for it to work.
For Django code, not in template the support is actually quite simple.
In settings change the timezone:
TIME_ZONE = 'Asia/Kolkata'
And where you need to use, use the following code:
from django.utils import timezone
now = timezone.now()
Source: https://docs.djangoproject.com/en/2.1/topics/i18n/timezones/
You can use time.strftime() for printing the current time. In your urlpatterns, just change '^time/$' to '^/$' to map the root page to your time function.

Categories