How to display current year in Flask template? - python

I am looking to find out how to output the current year in a Flask template. I know in Django you can use {% now "Y" %}., but is there a Flask equivalent? I have been unable to find anything during my research thus far.

Use a template context processor to pass the current date to every template, then render its year attribute.
from datetime import datetime
#app.context_processor
def inject_now():
return {'now': datetime.utcnow()}
{{ now.year }}
Or pass the object with render if you don't need it in most templates.
return render_template('show.html', now=datetime.utcnow())

For moment there is Flask Moment. It is powerful like Moment, and easy to use in Flask. To display the year in the user's local time from your Jinja template:
<p>The current year is: {{ moment().format('YYYY') }}.</p>

If using Jinja2 is too cumbersome and you are using Jinja2 in a context of a browser that you can simply use Javascript.
Using Simple Javascript
<span id="year"></span>
const year = document.querySelector('#year');
if (year) {
year.innerHTML = new Date().getFullYear().toString();
}
JavaScript library like moment.js
<script>
document.write(moment("2012-12-31T23:55:13 Z").format('LLLL'));
</script>

Related

Set the default template filter for the context_processor in flask

In my flask app i have these codes:
from __main__ import app
#app.context_processor
def breakline():
return { 'break': '<br>' }
How to use in html format is as follows:
{{ break }}
The above code works but there is a problem; A safe filter is needed to detect <br>; But I do not want to be added in html format every time like this:
{{ break | safe }}
I want this safe filter to be applied automatically and no longer need to be used in the html page. Is such a thing possible?
This is just an example and I do not just want to be able to create a <br>. I want to know if a filter can be added to a context_processor or not.
You can mark your html code as safe by using Markup.
from flask import Markup
#app.context_processor
def breakline():
return { 'break': Markup('<br>') }

Comparing dates using a comparator inside Django template

I am trying to compare the end date of an event with today's date to see if the event has ended. If the event has ended, the website user would not have a button to enrol and if the event has not started or is ongoing, the user would have a button to enrol in html.
I have tried this in my html template:
{% if event.end_date|date:"jS F Y H:i" <= today|date:"jS F Y H:i" %}
{% include 'event/includes/enroll.html' %}
But the button shows whether or not the event has ended already.
I wanted to add a method in my django model like this:
#property
def is_today(self):
return self.datefinish == datetime.today().date()
But I am not sure how to import the method and use it in html template then.
I wanted to try to add a variable in my view like this: (Django - Checking datetime in an 'if' statement)
is_today = model.end_date >= datetime.today()
return render_to_response('template.html', {'is_today': is_today})
But a colleague has written a Class-based view to render the template and not sure how to add the variable to render using the class-based view. I also got an error:
TypeError: '>=' not supported between instances of 'DeferredAttribute' and 'datetime.datetime'
If anyone can advice on how to best achieve what I need, I would be grateful :D
Hello why dont you use a custom_filter, that will return True or False in your template ? (https://docs.djangoproject.com/fr/3.1/howto/custom-template-tags/):
import datetime
from django import template
from django.conf import settings
register = template.Library()
#register.filter
def event_ended(date_event):
return date_event >= datetime.date.today()
{% load poll_extras %}
{% if event.end_date | event_ended %}
{% include 'event/includes/enroll.html' %}
The link from the documentation told you where to put the custom template

How to parse "2015-01-01T00:00:00Z" in Django Template?

In my Django html template, I get my SOLR facet_date result using haystack in the format
"2015-01-01T00:00:00Z". How can I parse it in format "01/01/2015" in my template?
My template is
{{ facets.dates.created.start }}
What "|date:" option should I add to my template?
Thanks!
If your date is a ISO string instead of a Python datetime.datetime, I guess you will have to parse it on the view or write a custom filter:
# yourapp/templatetags/parse_iso.py
from django.template import Library
import datetime
register = Library()
#register.filter(expects_localtime=True)
def parse_iso(value):
return datetime.datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ")
Then at the template:
{% load parse_iso %}
{{ value|parse_iso|date:'d/m/Y'}}
[edit]
got this error Exception Type: TemplateSyntaxError at /search/ Exception Value: 'parse_iso' is not a valid tag library: Template library parse_iso not found
Make sure you follow the code layout prescribed in the docs:
yourapp/
__init__.py
models.py
...
templatetags/
__init__.py
parse_iso.py
views.py
Your country may use m/d/Y (01/01/2015 is ambiguous, I suggest using an example like 31/01/2015 so it is clear if the first number represents day or month).
If {{ facets.dates.created.start }} is a datetime object then you can use
{{ facets.dates.created.start|date:"SHORT_DATE_FORMAT" }}
In case you are providing a string you can create a template filter to convert the string to datetime object and apply the date filter
#register.filter
def stringformat(value, args):
return datetime.strptime(value, args)
In the template:
{{ facets.dates.created.start|stringformat:"%Y-%m-%dT%H:%M:%SZ"|date:"SHORT_DATE_FORMAT" }}
You can use Django template tags for this. You need to use {{my_date|date:"some_format"}} which takes "my_date" as the argument (it should be a date object) to "date" tag and then formats it based on the given format.
{{facets.dates.created.start|date:"d/m/Y"}}

Passing django settings to django template using angularjs

I have this settings.py that include my global_constants.py
Now I want to access the Constants that I have defined in my global_constants.py in my Django Template using Angular JS. How to do that?
My global_constants.py contaains the following function:
def my_image_urls(request):
return {
"URL_ONE": "http://mywebsite.com/IMAGE/Image_one",
"URL_TWO": "http://mywebsite.com/IMAGE/Image_two",
}
Now I want to Access this URL_ONE and URL_TWO in my template/index.html which is called by my Views.py. But MY PURPOSE IS TO CALL THIS USING ANGULARJS into my template. How exactly I can achieve that. Need an overview so that I get on right direction :)
How I want to use it in my Templete is like this:
{{ URL_ONE }} /myimage.jpeg
{{ URL_TWO }} /myimage_two.jpeg
PLEASE NOTE THAT I AM USING ANGULARJS FOR MY TEMPLATE
For getting values from django into angularjs there are two main ways:
Create a view that returns JSON
In the view that serves your angularjs application, use django templates to encode extra information either into a script tag or data attributes.
So if you absolutely do not want to use any django templating then your angular js app will need to call your JSON settings view.
If you wish to eliminate that initial round trip then use django templating to inject your values into javascript:
<script type="text/javascript">
var DJANGO_URLS = {URL_ONE: "{{URL_ONE}}", URL_TWO: "{{URL_TWO}}"};
</script>
Your angular app can now access the variables globally (ie window.DJANGO_URLS).

How to Embed a Template Variable Inside a Hyperlink - Django Template

I am brand new to web development, Django, python, html, etc. I have a basic Django app that displays a list of publication titles that have been entered into the database. This works fine.
I now want to make it so that each publication title is a link that - when clicked on - renders another template with the details of the publication that was clicked. So far, I know how to get the publication link to render a template, but I am trying to figure out how to pass in the publication title to the hyperlink so that the data that is rendered in the details template will be specific to the title that was chosen.
Here is what I have in my publication template which displays all the publications (it is incorrect, but hopefully it clarifies what I am trying to do):
<html>
<head><title>Publications</title></head>
<body>
<h1>Publications</h1>
<ul>
{% for publication in publication_list %}
<li><strong>{{ publication.title}}</strong></li>
{% endfor %}
</ul>
</body>
</html>
For the sake of context, the url pattern that handles this is:
url(r'^(?P<detail_type>\w+)/(?P<link_item>\w+)/detail$', get_details)
And the view function is:
// note: I may have some of the logic/syntax wrong here, but this is the basic idea
def get_details(request, detail_type=None, link_item=None):
if detail_type == "publications":
publication = Publication.objects.filter(title__iexact=link_item)
return render(request, 'publication_detail.html', {'detail_type' : detail_type, 'publication' : publication})
elif ....
Like I said, I am very much a beginner so if I am approaching this in wrong way, any suggestions or resources are appreciated. Thanks.
If you use named url patterns you can easily do this with the url template tag.
urls.py
url(r'^(?P<detail_type>\w+)/(?P<link_item>\w+)/detail$', get_details, name='details')
template
{% url 'details' 'publications' publication.title %}
I hope you know about SlugField too, it is much better for urls than a normal CharField.
An alternative:
urls.py
url(r'^(?P<detail_type>\w+)/(?P<pk>\w+)/detail$', get_details, name='details')
template
{% url 'details' 'publications' publication.pk %}
views.py
def get_details(request, detail_type=None, pk=None):
if detail_type == "publications":
publication = Publication.objects.get(pk=pk)
return render(request, 'publication_detail.html', {'detail_type' : detail_type, 'publication' : publication})
elif ....
This uses the primary key of the entry instead of the title. If you want to have a url with the title in it you will want to add and use a SlugField on your model.
This looks pretty good to me, although you may want to use get as opposed to filter in your view function if all the publication titles are unique and you want to pass an instance of Publication rather than a queryset (containing one item) into the detail template. This would throw an error of there were 0 or >1 matches, but it sounds like that's probably the behavior you'd want
However, I'm not sure what it is that you're missing here. What does publication_detail.html look like? You should have essentially everything you need in the above code to render the details, assuming they're all contained in the relevant Publication instance.

Categories

Resources