This is driving me crazy, feels like it should be easier.
Using Jinja code for a HTML email, in a drag and drop editor - so no access to the <head>!
I have a date I’ve set as a variable the date format is YYYY-MM-DD HH:MM:SS
I want to change the format using datetimeformat function, it works fine as {{ today()|datetimeformat("%y-%m-%d") }} - but I'll be buggered if I can exchange today() with my variable.
{% set bonusBeforeDate = linkedData.accessCodes[userAttribute['ReferralSource']]['promotion']['rules']['member_joined_date']['before'] %}
And then
{{ bonusBeforeDate|datetimeformat("%y-%m-%d") }}
OK, someone very kind has helped me out with this one, so I'll share it here in the hope it saves anyone else the headache later.
The reason it is not working is because datetimeformat requires datetime object, while yours is a string. The today() function returns datetime object, so it works directly. You will have to perform some transformations to get this working. The following sequence needs to be followed:
Convert your string to another suitable string to represent datetime object. Not all date looking strings can be converted to datetime object, they need to follow a specific format.
Now convert the new string to a datetime object (strtotime)
Apply any datetime formatting to the date time object (datetimeformat)
In practical terms with your example:
Step 1:
{% set myDate='2020-12-31 12:59:00' %}
{% set myDateFormatted = myDate|split(' ',2) %}
{% set myDateFinalFormat = myDateFormatted[0]+'T'+myDateFormatted[1]+'Z' %}
The value of myDateFinalFormat at this point should be 2020-12-31T12:59:00Z which is the exact string format we are interested in.
Steps 2 and 3:
{{ myDateFinalFormat|strtotime("yyyy-MM-dd'T'HH:mm:ssXXX")|datetimeformat("%y-%m-%d") }}
This will output: 20-12-31
Related
I'm using Django template filters to format a datetime instance, but it looks like its value differs from raw date in the datebase.
I used datetime.now() in Python to create the instance.
{{ modeltest.date }}
will show
"Jan. 3, 2019, 5:27 a.m."
on the page, but
{{ modeltest.date | date:"Y-m-d H:m:s" }}
displays
"2019-01-03 05:01:19"
Note the difference of the minutes displayed (5:27 vs 05:01)
I'm getting a little confused here.
Does anyone know this?
You mixed up the date filters. You used the month twice (lowercase m) instead of using minutes (lowercase i).
You are seeing "2019-01-03 05:01:19" (with the minutes as 01 instead of 27) because it actually show the month (January is the first month, so 01).
You can change this
date:"Y-m-d H:m:s"
to
date:"Y-m-d H:i:s"
I have series of aggregations in DJANGO that I am performing. What I want to know, is if there is a way to {{ template }} a particular row-value from a dataset.
For example: If I have this dataset response from the server:
[{ type:'O', count:54},{ type:'E', count:125},{ type:'C', count:2}]
Can I reference the counts by type in the template without going through the foreach command?
For example: officers: {{ variable.O.count }} or something like that so I can just directly reference the value in a specific row?
The only other option I have right now, is to call the database three times. And I'm hoping not to have to do that.
Thank you.
To be brief.
next_contact is a UTC datetime
When I write in template
{{ event.next_contact }}
I get properly localized date and time
But in this place I want output only time so I do:
{{ event.next_contact.time }}
and then I get non localized time
How to fix it??
Use {{ event.next_contact|localtime|date:"H:i" }}. If you have set USE_TZ=True you can skip the localtime filter.
As of Django 1.7 when passed a datetime value with attached timezone information (a time-zone-aware datetime instance) the time filter will accept the timezone-related format specifiers 'e', 'O' , 'T' and 'Z'.
Instead of using the attribute, just use the time filter on the datetime:
{{ event.next_contact|time }}
i want to display time in 12 hour format in django templates as iam storing time data in a charecter eg('18:30:00') field how to convert this string time data to date in django/python?
If you absolutely must do this, use time.strptime. It would be a better idea not to store structured data in a string if you can avoid it, though.
Within Django's templates you can use the date Template Filter:
{{ value|date:"h:i:s a" }} # '18:30:00' would appear as 6:30:00 p.m.
{{ value|date:"g:i:s a" }} # '18:30:00' would appear as 06:30:00 p.m.
value would be the string variable you pass in the Context to the Template when you render it. The string appearing after date: formats the time.
You can find more here: http://docs.djangoproject.com/en/1.3/ref/templates/builtins/#date
Hank Gay's answer is more correct than mine; you should avoid keeping structured data in a string if at all possible.
I have a form select box that has values corresponding to objects. The user selects an input and the form submits. I then want to take that value and retrieve the object that has an ID equivalent to the selected form value. However, when I try to do so, I'm getting an error like so:
int() argument must be a string or a number, not 'Cars'
Example:
if form.is_valid():
car = Car.objects.get(id=form.cleaned_data['id'])
I'm guessing the problem is that the returned value is a string and NOT an integer. In PHP this is SIMPLE. How do I typecast or use the returned form value to get an associated object?
Seems as though Django is not returning the value of the form element, but instead the user visible option name...
Form Class:
class CarForm(forms.ModelForm):
class Meta:
model = Car
Html Form:
<form action="">
<select name="id">
{% for car in cars %}
<option value="{{car.id}}">{{car.title}}</option>
{% endfor %}
</select>
</form>
The id field has to be an integer, or a string that can be converted to an integer.
Simple as that!
Somehow, your form.cleaned_data['id'] is returning a model called Cars
Ensure it returns a number if you want to pass it into get(id=
You can use ModelChoiceField instead of generating the select using HTML
in forms.py:
class CarSelectForm(forms.Form):
car = forms.ModelChoiceField(queryset=Car.objects.all(), empty_label=None)
in view.py:
if form.is_valid():
car = form.cleaned_data['car']
This is maybe a bad, but I think working answer. If anyone has a real solution, please post because I still need it.
(I'm using a modelformset, but just a modelform may work the same)
For me, the {{ form.id }} works on the page (puts the id) and comes back correctly in the POST data. However, somewhere along the line it gets converted (as Yuji said in his post) into the model object represented by that id and that is what is in cleaned_data.
In short, change
car = Car.objects.get(id=form.cleaned_data['id'])
to
car = form.cleaned_data['id']
I think it just looks like a string just because when you print or debug, it's using your str or unicode representation.
Repeat: This is almost certainly a side effect or bad way to do things. If I figure out a better way, I'll post it.
I have the same issue... so I tried the following:
ts_1 = form.cleaned_data['lista_trabajos']
ts_2 = request.POST['lista_trabajos']
print(ts_1) # this returns what user sees, ex: 1 - folders
print(ts_2) # this returns value from that option, in my case: 1
Unfortunately, I have been reading that by using raw POST data is not recommended. At the moment, I cannot figure out how to validate and get the raw POST data by using something similar to "clean_data".
You can read about this in: https://books.google.com.ar/books?id=8sU7DwAAQBAJ&pg=PA229&lpg=PA229&dq=form+cleaned_data+to+get+raw+post+data&source=bl&ots=RN9WKRaGJs&sig=QpSoPdI9YSHSNk0zAQIO8phSbOw&hl=es&sa=X&ved=0ahUKEwiBouHattnaAhULFZAKHUKmA4QQ6AEIRzAD#v=onepage&q=form%20cleaned_data%20to%20get%20raw%20post%20data&f=false