Save Datetime in variable to reflect in HTML Django/python - 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.

Related

Using a jinja variable in JS script

I'm new to Flask and looking for a way to parse one or n values of a jinja variable.
The app route hands an object over to the html template.
`selection2 = db.execute("SELECT user.id, bikes.id, bikes.name, bikeshopname, price, city, img, enddate FROM user LEFT JOIN bikes ON user.id = bikes.userid LEFT JOIN renthistory ON bikes.id = renthistory.bikeid WHERE user.city = :city AND price NOT NULL", city=select_city)
return render_template("/bikes.html", selection2=selection2)`
In the template I implemented it like this:
{% for row in selection2 %}
<p id="enddate" value="{{row["enddate"]}}"></p>
{% endfor %}
In the js function I get the value (a certain date) of that particular paragraph. So it works for the first item.
function getBikeRentEndDate() {
let enddate = (document.getElementById("enddate").innerHTML);
document.getElementById('showdate').innerHTML = enddate;
}
But what I want is to look in all the created once the template is rendered. And then show a message if a condition is true. Something like "if date is => today - show a message.
I know there is a way but after researching and trail and erroring for quite a while, I hope someone can point it out.
To achieve the desired result, you have to first cast the jinja2 variable to js.
To do that in your template:
<script>
const listselection2 = JSON.parse('{{ selection2 | tojson | safe }}');
//do your stuff with listselection2.
</script>

Pass Django variables between view functions

I'm asking a question about variables handling in my Django application view.
I have 2 functions :
The first one lets me to display query result in an array with GET filter parameter (in my case, user writes year and Django returns all objects according to this year. We will call query_naissance this variable).
The second one lets me to create a PDF. I have lots of variables but I want to take one more time query_naissance in my PDF.
This is my first function :
#login_required
def Table_annuelle_BirthCertificate(request) :
query_naissance = request.GET.get('q1')
...
return render(request, 'annuel.html', context)
And my second function looks like :
#login_required
def Table_Naissance_PDF(request) :
data = {"BirthCertificate" : BirthCertificate}
template = get_template('Table_raw.html')
html = template.render(Context(data))
filename = str('Table annuelle Naissance.pdf')
path = '/Users/valentinjungbluth/Desktop/Django/Individus/' + filename
file = open(path, "w+b")
pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8')
file.close()
context = {
"BirthCertificate":BirthCertificate,
"query_naissance":query_naissance,
}
return render(request, 'Table.html', context) # Template page générée après PDF
So How I can add query_naissance given by user in my first function to my second one without write one more time a field ?
Then, I have to call this variable like {{ query_naissance }} in my HTML template.
Thank you
In order to persist information across requests, you would use sessions. Django has very good session support:
# view1: store value
request.session['query_naissance'] = query_naissance
# view2: retrieve vlaue
query_naissance = request.session['query_naissance']
# or more robust
query_naissance = request.session.get('query_naissance', None)
You need 'django.contrib.sessions.middleware.SessionMiddleware' in your MIDDLEWARE_CLASSES.

Time limit in django template

I need a help with time-limit. I want to show user how many time he has got to rent a car.
This is my views:
class CarRentView(RedirectView):
permanent = False
query_string = True
model = Car
def date_of_return(request):
car = Car.objects.all()
car.rent = True
date_of_rent = datetime.now()
date_of_rent = car.save()
car_return_date = date_of_rent+timedelta(days=30)
return render(request, 'cars','car_return_date')
and when I want to do this in my template:
{{ car_return_date }}
there is nothing and I don't know, what's wrong. Is there any possibility to show return date and after this make a count?
You need to call the render function differently:
return render(request, 'myapp/index.html', {'cars': car, 'car_return_date': car_return_date})
See the docs for more information.
Besides, I don't think you are setting the car.rent correctly, since you are setting it on all cars.
Variables that you return to your template need to be returned as part of a context dictionary. So you would have:
return render(request, 'my_template.html', {'car': car, 'car_return_date': car_return_date})
The car_return_date variable will then be available in your template using:
{{ car_return_date }}
You will also probably want to use the date filter when outputting the datetime object. For example, you could use:
{{ car_return_date|date:"j N Y" }}
I would suggest changing date_of_rent to last_date_of_rent by adding 30 days to it. And then, saving last_date_of_rent to the models. So you can use, last_date_of_rent directly in the templates. Further the use of in-built template filter timeuntil will return the desired. -
{{ car.last_date_of_rent|timeuntil }}
Documentation:
https://docs.djangoproject.com/en/1.11/ref/templates/builtins/#timeuntil

Django Links by Month

I'm having trouble figuring out how to create links on a blog I'm making. I want my index page to have links to blog posts grouped by year/month.
Here is my view that will display the all the blog posts by month/year (the url will look like 2014/10 if I want to see the blog entries from October 2014):
def month(request, year, month):
month_entry_list = Entry.objects.filter(pub_date__year=year, pub_date__month=month)
return render(request, 'blog/list_post_by_month.html', {
'month_entry_list': month_entry_list
})
Here is my index view:
def index(request):
# latest_entry_list = Entry.objects.order_by('-pub_date')[:5]
entries = Entry.objects.all().order_by('-pub_date')
latest_entry_list = entries[:5]
template = loader.get_template('blog/index.html')
context = RequestContext(request, {
'latest_entry_list': latest_entry_list
})
return HttpResponse(template.render(context))
I have an idea of how to go about this but I'm not sure it's optimal. Should I just query the database to get a list of all the year/month combinations, and use that to create links in the index template?
Maybe you could keep the relevant month-years in server-side cache (https://docs.djangoproject.com/en/dev/topics/cache/) and just update it occasionally by appending to it (i.e. just checking for more posts since the last month that had one.)

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

Categories