After extensive googling, I still havent come up with an effecient way to solve this.
Im creating a website using Django. I have a db which contains time data, more specifically dates. The value for "the present" is set to 3000-01-01 (YYYY-MM-DD) as is common practice for time-querying.
What I want to do is display a string like "Now" or "Present" or any other value instead of the date 3000-01-01. Is there some sort of global override anywhere that I can use? Seems like a waste to hard-code it in every view/template.
Cheers!
Since this is rendering, I would advice against "subclassing" the DateField such that it renders 'now' instead of the original date(..) object: it will make calculations in the model layer more cumbersome.
Probably a good way to deal with this is implementing a template filter [Django-doc], for example we can construct a file:
# app/templatetags/nowdate.py
from django import template
register = template.Library()
PRESENT = date(3000, 1, 1)
#register.filter
def nowdate(value):
if value == PRESENT:
return 'present'
return value
The templatetags directory of the app application, needs to contain an __init__.py file as well (an empty file), and the app of course needs to be part of the INSTALLED_APPS in the settings.py.
Then we can use it in the template like:
<!-- app/templates/app/some_template.html -->
{{ some_model.some_date_field|nowdate }}
Here we thus fetch the some_date_field of the some_model variable (this attribute is thus a date(..) object), and we pass it through the nowdate filter we have constructed such that, if it is 3000-01-01, it is replaced by the 'present' string.
The advantage here is that if we later change our mind about what date the "present" is, we can easily change it in the template filter, furthermore we can easily extend it, for example by adding a 'past', 'future', etc.
Related
I am trying to add extra data to a form field in wtforms.
I have to create a text field which has an associated unit with it (eg - meter/sec). How do I add the meter/sec string to the form field?
Is there any way to pass a dictionary or something to add data to the field that i can access in the template?
There is a not very well known parameter, description= to the field constructor. Though it purports to be for help text, the framework itself doesn't care what you put in there (and indeed doesn't use it anywhere at all, other than passing it along.)
So you could do, for example:
class PhysicsForm(Form):
speed = TextField('Speed', description={'unit': 'meters/sec'})
distance = TextField('Distance', description={'unit': 'kilometers'})
Then you could use it in a jinja-style template something like:
{{ form.speed }} <label>{{ form.speed.description.unit }}</label>
footnote There was no real reason for using a dictionary as the value of description - it was merely to illustrate that you can put nearly any value in there, including containers which can hold many values.
In Django, I want to use a specific filter in all of my templates for all variables of a specific type.
For example let's say I want to use a filter that will convert date to Jalali Calendar if necessary based on user settings. In this case I want this filter to be applied to all variables I'll use in my templates that are a date.
I have a template called base.html which all of my templates extends it.
How can this be accomplished?
UPDATE: I'll use an example to clarify what I want to do exactly.
I have a model called Post which has field called publish_date. sth. like this.
class Post(models.Model):
title = models.CharField()
content = models.TextField()
publish_date = models.DateTimeField(auto_now_add=True)
Now when I'm outputting a post using a template I want all of my posts publish_date and all of my other variables in the template which are representing a date to be filtered using a filter called jalali_date. which will format dates to sth I want.
I know how to use custom tags and filters but I don't know how to accomplish sth. like this using them(if it's possible to do this using them).
UPDATE 2:
Just to more clarify: I have already written jalali_date filter. the problem is how to apply it automatically to all variables in my template that are a date.
If you want to implement this by a custom filter read about filters here, also below code maybe can help you:
import datetime, time
from django import template
import khayyam
register = template.Library()
def jalali_date(date):
"""Converts Date into JalaliDate"""
timestamp = time.mktime(datetime.datetime.timetuple(date))
jalali_date = khayyam.JalaliDate.fromtimestamp(timestamp)
return str(jalali_date)
register.filter('jalali_date', jalali_date)
and then in template you can use it similar below(suppose templatetag file nam is jdate):
{% load jdate %}
...
{{ publish_date|jalali_date }}
...
but if you want to automatically recognize and change values of certain types you must use MiddleWares (not filters), read snippet code about a custom MiddleWare here.
Note: for using non-builtin filters, you must add container app in INSTALLED_APPS.
I am trying to access elements of a dict with keys that start with the underscore character. For example:
my_dict = {"_source": 'xyz'}
I'm trying to access them in a Django template. Obviously I realise that you can't access underscored python variables from a Django template (because they are considered private in Python) but this is a dict object where any immutable object is a valid key.
I can't access the above dict in a Django template using {{ my_dict._source }} so I assume Django is preventing it. Is that accurate?
I am kind of hoping Django does something sane with variables that start with underscore like still doing dict lookups (the first thing is supposedly tries) but refuses to do attribute lookups, method calls and list index lookups since an underscored prefixed variable would be invalid. I am quickly loosing hope though.
For the record, I know someone will suggest to just change the dict but this is actually a multi-levelled dictionary returned by the rawes library when executing REST API request on a ElasticSearch instance.
The docs mention that you can't have a variable start with an underscore:
Variable names must consist of any letter (A-Z), any digit (0-9), an underscore (but they must not start with an underscore) or a dot.
but you can easily write a custom template filter to mimic the dictionary's get method:
#register.filter(name='get')
def get(d, k):
return d.get(k, None)
and
{{ my_dict|get:"_my_key" }}
In my case, if I know the dict elements, and it's only one, I prefer to rename the dict key using pop:
my_dict['new_key'] = my_dict.pop('_old_key')
That way I get a new name on the dict, and I can access in the template without problems.
I wish to add custom input field attributes to the default event page template (or rather extend it). I don't know which is the template for the same and where is it located in ZMI.
F.e. I wish to add custom metadata like client name, lawyer name etc. I know how to add the metadata for the same but how to extend the event's default template.
Other option: If I use ploneformgen for the same, how can I get the calendar view for the events created? Finally wish to have calendar view for the custom data input with the start and end date for input created, which is searchable. The data for the collection should be searchable and should have 'hyperlinks to the folders' containing the related documents in the tabular view?
I am using zettwerk.fullcalendar for plone 4.1
To add extra fields to the existing Event type, using http://pypi.python.org/pypi/archetypes.schemaextender
It's not something you can do TTW.
Found the template at /site/portal_skins/event_view which you can customize. At least know where to start with. But when I use the customize tab, I get the error for the python expression witout changing the code as :
Macro expansion failed : widget
On testing, it shows error with the python expression:
Module Products.PageTemplates.ZRPythonExpr, line 48, in call
__traceback_info__: context.start().Date() == context.end().Date()
Module PythonExpr, line 1, in
The template code is :
<tal:differentday tal:condition="python:context.start().Date() == context.end().Date()"
i18n:translate="event_when_differentday">
Can anyone guide as to what the error in the above expression is?
Possibly i am overlooking an obvious solution or thinking the wrong way...
I have a limited amount of text, words in a database, that I want to display translated to users in a flask/jinja/babel webapp. eg. "running" is a possible value of an "activity" column and that should be "laufen" for my german users.
Words in templates and code are extracted and put into the catalog, but how do i get additional words into the catalog? Is there a simple text file extractor?
The only thing i could think of is, just create a .py file and put lots of _('...') lines in them, but that feels just wrong... is it?
I created a messages.txt with my "words" like gettext function calls:
_('cycling')
_('running')
and added it to my babel.cfg as python source:
[python: messages.txt]
plain, simple, stupid, but works.
First, start with http://flask.pocoo.org/snippets/4/.
Secondly, you need to store these 'limited' values as integers or enums in database and then create the lookup table for all these enums in code (so Babel knows about them):
i18n_val = {0: _('running'), ...}
# Or multi-level dict with different categories:
i18n_all = {
'activity': {
0: _('running'), ...
'foo': {
0: _('bar..'), ...
}
}
And accessing the translated string from template is now as simple as:
{{ i18n_val[obj.activity] }}
{{ i18n_all['activity'][obj.activity] }}
In order to make the i18n_val and i18n_all variables available for all the templates, just register them with context processors.