print page generation time - python

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

Related

Pass GET parameters through django's render() shortcut

I have a date filter that I am passing through several django views:
views.py
def event_list(request):
date_query = request.GET.get("date", str(default_event_date()))
d = datetime.strptime(date_query, "%Y-%m-%d").date()
# do stuff...
return render(request, "events/event_list.html", context)
But I would like to carry forward the GET parameters through the render().
I've found this answer for how to do this using reverse(), but render() doesn't take a url directly.
I suspect I need to add it back in to the request that is passed, but I'm not sure how to do this.
I think you are misunderstanding render. render’s job in life is to return an HttpResponse with content to the user from an HTML template and a context dictionary:
Combines a given template with a given context dictionary
and returns an HttpResponse object with that rendered text.
In contrast, redirect redirects the user to a new URL (i.e., so GET parameters can be included). Thus, if you use render, you have to preserve your GET parmeters manually. Of course, you can avoid this by adding date to the user’s session by doing something like:
from datetime import date, datetime
date_query = request.session.get('date')
if not date_query:
date_query = request.GET.get("date", default_event_date())
if not isinstance(date_query, date):
date_query = datetime.strptime(date_query, "%Y-%m-%d").date()
request.session['date'] = date_query
d = date_query
And this will let you “carry forward” your GET parameters to subsequent routes and views.

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.

Distinguish a user depending on which page he comes from. Django

I would like to know if there is a way to differentiate a user depending on which page he comes from.
In my template, I would like to display something only if the user comes from a specific view (I wan't to display the same page I display for the others users, but adding a popup telling him something).
Is there a way to do that?
Thank you for your help
If possible, use HTTP_REFERER request header. This works in most cases. If it doesn't, then you'll have to maintain it in the session.
To know what view function would a URL call, use django.core.urlresolvers.resolve. I think this is not documented but it's pretty straight forward, example:
In [1]: from django.core import urlresolvers
In [2]: urlresolvers.resolve('/admin/')
Out[2]: ResolverMatch(func=<function index at 0xadb1924>, args=(), kwargs={}, url_name='index', app_name='admin', namespace='admin')
In [3]: urlresolvers.resolve('/admin/').func
Out[3]: <function django.contrib.admin.sites.index>
Now, using that against the HTTP_REFERER in a custom template filter could look like this:
from django import template
from django.core import urlresolvers
from yourapp.views import specific_view
register = template.Library()
#register.filter
def comes_from_specific_view(request):
if not request.META.get('HTTP_REFERER', None):
return False
return urlresolvers.resolve(request.META['HTTP_REFERER']).func == specific_view
In template:
{% if request|comes_from_specific_view %}show popup{% endif %}
There are several ways to do that:
You can set a cookie in the first view, and check its value in the destination view. Don't forget to clean the cookie if the user goes through another page in between. Downside is that the user can disable cookies in his browser.
Depending on the way the user goes to the destination view (a link or a form), you can use a GET or a POST parameter.
Use sessions
The most straightforward general way I can think of is making a middleware class that saves the previous request path in the user session and then using {{ user.session.previous_page }} in the template. For example:
class ReferrerMiddleware(object):
def process_request(self, request):
if request.user.is_authenticated():
request.user.session['previous_page'] = request.session['current_page']
request.user.session['current_page'] = request.path

Calculate number of days between two dates inside Django templates

I have two dates and want to show a message like "n days left before your trial end." where n is a number of days between two given dates. Is that better to do this inside views or is there a quick way to do it inside template itself?
Use timesince template tag.
This code for HTML in Django. You can easily find the remaining days.
{{ to_date|timeuntil:from_date }}
Otherwise, you can use custom TemplateTags.
Possible duplicate here
I'd actually use the same method lazerscience uses, something like this:
from datetime import datetime, timedelta
from django import template
from django.utils.timesince import timesince
register = template.Library()
#register.filter
def time_until(value):
now = datetime.now()
try:
difference = value - now
except:
return value
if difference <= timedelta(minutes=1):
return 'just now'
return '%(time)s ago' % {'time': timesince(value).split(', ')[0]}
In the HTML template, you can do the following:
{{ comments.created|timeuntil:project.created }}
And you get output something like this:
1 hour, 5 minutes

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