error using DatePicker, I keep getting Not a valid date value even with the correct formatting. I need help, I can't figure out what is wrong - flask-wtforms

I am working on a project and one of the modules are related to an appointment site using wtfform+DataField+flask
My form in appointment.html looks like this:
<form action="#" method="post" name="myform">
{{ form.csrf_token }}
{{ wtf.quick_form(form, novalidate=True, button_map={"submit": "primary"}) }}
my forms.py:
class DateForm(FlaskForm):
date = DateField("Date", format="'%Y-%m-%d'", validators=[Optional()])
hour = TimeField("Hour", format="'%H:%M'", validators=[Optional()])
submit = SubmitField("Submit")
My main.py
#app.route("/appointment", methods=["GET", "POST"])
def appointment():
form = DateForm()
if form.validate_on_submit():
session["date"] = form.date.data
session["hour"] = form.hour.data
return redirect(url_for('date'))
return render_template("appointment.html", form=form, current_user=current_user)
#app.route('/date', methods=['GET', 'POST'])
def date():
date = session["date"]
hour = session["hour"]
return render_template('date.html')
I have tested other alternatives but with the same result. No matter what, I'm still seeing the "Not a valid date value" and "Not a valid time value" messages.
I appreciate any help.
Thanks!!!
appointment

I've already solved this problem by adding InputRequired() as validator y the form, just like this:
date = DateField("Fecha", validators=([InputRequired(), DataRequired()]))
hour = TimeField("Hora", validators=([InputRequired(), DataRequired()]))

Related

How to get the actual meridiems in luxonjs?

So i tried to get the meridiems on luxon.js because i'm going to move my discord.js bot that is using momentjs to luxonjs because i like it more. But i got the problem that i just can't figure out how to get the meridiems of the timezone that i especify, could you help me out?
I've tried
Info.meridiems()
but i don't know how to use or what do i do with the Info part,
And then i don't understand the parameters that the give in their documentation as an example
Info.meridiems({ locale: 'my' })
it was kinda easy but i will not delete this post if someone needs it.
Basically what i did is to get the date in the format that i wanted
const time = DateTime.local().setZone('tz').toFormat("HHmmss");
in .setZone('tz') you should just put the time zone you want according to the luxon docs.
Then i would just use an if for it
const smartMeridiems = (am, pm) =>{
if(time > 120000){
pm = 'PM'
return pm;
} else{
am = 'AM'
return am;
}
}
And that is basically it
The meridiem for a DateTime can be accessed by the "a" format token:
DateTime.local().setZone(z).toFormat("a") //=> "PM"
The Luxon Info methods are for finding out what the meridiems are called in different human languages.

Flask - Flask-Moment gives out an error: AttributeError: 'str' object has no attribute 'strftime'

Ok, so i want to change a datetime value from mysql database into a desired format. so my code goes:
file: app.py
from flask import Flask, render_template, flash, redirect, url_for, session, request, logging
from datetime import datetime
from flask_moment import Moment
app = Flask(__name__)
moment = Moment(app)
mysql = MySQL(cursorclass=DictCursor)
#app.route('/users')
def users():
# create cursor
cur = mysql.get_db().cursor()
# execute query
cur.execute('SELECT * FROM users')
# get results
users = cur.fetchall()
return render_template('users.html', title = 'User Accounts', users=users)
then on my users.html, i display the datetime value on a table which goes:
file: users.html
<tbody>
{% for row in users %}
<tr>
<td>{{row.id}}</td>
<td>{{row.username}}</td>
<td>{{row.fullname}}</td>
<td>{{moment(row.created_at).format('LLL')}}</td> # this causes an error
</tr>
{% endfor %}
</tbody>
But when i put in the following code for the datetime:
<td>{{moment().format('LLL')}}</td> # this is working
So in short,
# this is not working
# Causes an "AttributeError: 'str' object has no attribute 'strftime'" error
moment(row.created_at).format('LLL')
# this is working
# but i can't modify the data based on the value from mysql database
moment().format('LLL')
# by the way, this is also not working
# and it also causes the same error
row.created_at.strftime('%M %d, %Y')
What i need to know is how to format datetime value in the flask template and Flask-Moment seems to be the only way
EDIT:
You can also try using:
{{ row.created_at.strftime('%M %d, %Y') }}
or the jinja datetime filter:
{{ row.created_at|datetime }}
ORIGINAL ANSWER:
It appears you need to convert from MySQL DateTime to Python datetime. Without seeing more of your code, maybe something like this would work, though there is probably a more efficient way:
# get results
users = cur.fetchall()
for user in users:
user.created_at = datetime.strptime(user.created_at, '%Y-%M-%d') # you have to use the mysql format here
return render_template('users.html', title = 'User Accounts', users=users)
You are using strftime when it appears that python is interpreting the MySQL datetime as a string, not a datetime() object, so you have to use strptime
Momentjs couldn't parse it because it is an 'str'. Use datetime to parse the string before passing it to the momentjs object e.g
from datetime import datetime
row_created_at = datetime.strptime(row_created_at, %m %d,%Y ')
then pass it to the momentjs object like so
{{moment(row_created).format("LLL")}}
That should do the trick

How can I use the actual datetime for a field in Odoo 11

I want some like datetime.now() or similar in Odoo 11 to get the actual date and time.
I tried the code I saw in another answers in stawoverflow, but doesn´t works for me. Can someone put an example for how to do it?
Examples that doesn´t works:
exit = fields.Datetime('Date current action', required=False, readonly=False, select=True, default=lambda self: fields.datetime.now())
exit = fields.Datetime(string="Date current action", default=lambda *a: datetime.now())
exit= fields.Date.context_today(self, timestamp=datetime.datetime.now())
from datetime import datetime
exit = fields.Date(string='Date Current Action',default=datetime.now())
Use:
default=fields.Datetime.now
You can find an example at sale.py.
The following explanation is taken from Odoo 11 ORM API
class odoo.fields.Datetime(string=, **kwargs)
...
For default values fields.datetime.now() should be used instead.
Edit
You can also use time module to set default values
default=lambda *a: time.strftime('%Y-%m-%d')
try to use lambda For example in Odoo 8 to Odoo 14 :
exit = fields.Datetime(string="Date", default=lambda *a: datetime.now())

Symfony, how to get localized date

most likely a silly question, but I do not see how to do.
Within a controller, I need to use $myObj->getData()->format('d-M-Y'), and I wish to get a localized string too (in italian instead than in english).
Within a twig template, I get it by {{ myobj.data|localizeddate('long', 'none', app.request.locale ) }}, but I do not know a similar trick for the former case.
Yes, I found how to do (thanks to ccKep):
$cal = IntlCalendar::fromDateTime($oldObj->getData()->format('d-M-Y')." Europe/Rome");
$newObj->setField("my date is ". IntlDateFormatter::formatObject($cal, "d MMMM YYYY", 'it_IT')."");
In controller you may use Intl. For example:
$intl = new \IntlDateFormatter($request->getLocale(), \IntlDateFormatter::LONG, \IntlDateFormatter::NONE, null, null, 'd-LLL-y');
$date = $intl->format(new \DateTime('now'));

plone.app.event- Using IEventBasic as a behavior, how can I properly set the end field programatically in an event?

I have a dexterity content type (my.product.myobject) that uses the IEventBasic behavior (implemented in the xml file with other behaviors) and I'm trying to make the end field be set within the same week of the start field. I attempt to correct the end date in an IObjectAddedEvent (zope.lifecycleevent.interfaces.IObjectAddedEvent).
I first get the week range from the start field:
def getWeekRangeFromDate(a_date,offset=1):
start = (a_date - timedelta(days=(a_date.weekday() + offset) % 7)).replace(hour=0,minute=0)
end = (start + timedelta(days=6)).replace(hour=23,minute=59)
return {'start':start,
'end':end,
}
def myObjectAdded(myObject, event):
week_range = getWeekRangeFromDate(myObject.start)
if myObject.end > week_range['end']:
myObject.end = week_range['end']
I have the end field printed in the browserview and I use IEventAccessor to extract the end date from the myObject:
class View(BrowserView):
def __init__(self,context,request):
...
self.context = self.context
def getFormattedEnd(self):
if self.context.whole_day == False:
return IEventAccessor(self.context).end.strftime('%m/%d %I:%M %p')
...
When it doesn't need to be programmatically corrected, the end field displays correctly, but when it does, it appears 5 hours off.
In my myObjectAdded event, I tried:
if myObject.end > week_range['end']:
myObject.end = week_range['end'] - timedelta(hours = IEventAccessor(myObject).end.offset().total_seconds()/3600)
This does appear right actually, but when I go to the edit form and change the start field, the end field ends up changing itself seemingly random. Changing the starting hour field to 16 changed the end's month about two weeks ahead.
How can I set it without it acting up? Am I misundertanding how to use IEventBasic?
Edit: I'm coming across something really interesting. In the edit form, the Start End Validator is failing.
Event Starts - 25/November/2016 9:00
Event Ends - 25/Novermber/2016 20:00
I click submit and the status message says End date must be after the start date.
Edit: The version of Plone I am using is 4.3.

Resources