Is there an easy way to implement DateTimePicker in Django Crispy forms? - datetimepicker

I have a DeliveryNote model which contains datetime field.
class DeliveryNote(models.Model):
date_completed = models.DateTimeField("Date Completed")
But on ModelForms, there is only DateField available:
date_completed = forms.DateField(initial=datetime.date.today,
widget=forms.widgets.DateInput(attrs={'type': 'date'}))
As it can be seen that there is not time selection:
I have looked to this answer, but can not able to implement it. Any idea how to implement datetime field easily.

You can use DateTimeInput widget and datetime-local as input type:
date_completed = forms.DateField(initial=datetime.date.today,
widget=forms.widgets.DateTimeInput(attrs={'type': 'datetime-local'}))

Related

How To Format And Bind Multiple SimpleObjectProperties<LocalDate> To A Label?

I am trying to create a calendar view in which there are events displayed with start and end times on one label. Something like:
2:30pm - 4:30pm
My model has a SimpleObjectProperty<LocalTime> for each of these times. I know that I could concatenate these by doing something like:
label(Bindings.concat(model.startTime, " - ", model.endTime))
But I would still need formatting for each time. Knowing how to do this would certainly help me in the future with other equally complex binding transformations. Or would it just be easier to attach listeners to each time property that would update the label text?
I think I found my own answer, but anyone can feel free to let me know if this is good practice or not.
root {
...
val timeFormat = DateTimeFormatter.ofPattern("h:mma")
label(stringBinding(model.startTime, model.endTime) {
val startTime = model.startTime.value
val endTime = model.endTime.value
"${startTime.format(timeFormat)} - ${endTime.format(timeFormat)}"
})
...
}

Compare dates in openerp 7

I have a custom module in openerp 7 with fields check-in time(date-time) and check-out time(date-time). When I click on save, i want to perform a validation on both fields to ensure check-out time is not less than check-in time. Thanks for any ideas.
As above, use datetime.
In Odoo your dates, times and datetimes are handed to use as strings formatted using
openerp.tools.DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_TIME_FORMAT and DEFAULT_SERVER_DATETIME_FORMAT.
from datetime import datetime
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
check_in = datetime.strptime(my_object.check_in, DEFAULT_SERVER_DATETIME_FORMAT)
check_out = datetime.strptime(my_object.check_out, DEFAULT_SERVER_DATETIME_FORMAT)
Go nuts with comparisons etc.
A couple of notes:
I highly recommend reading up on the datetime module in the standard library, particularly strftime, strptime and timedelta
Remember you will be getting the dates and datetimes in UTC. The classes that represent the date and datetime fields have methods to return dates and timestamps in the users' timezone but you will not usually need these. Have a look at fields.date.context_today and fields.datetime.context_timestamp
I would try to use the datetime class from the datetime module.
Import relevant python module
from datetime import datetime
Retrieve your record via the appropriate method i.e.
your_record = self.pool.get('your_custom_module').search(cr, uid, domain, offset=0, limit=None, order=None, context=None, count=False)
note: you need to provide proper domain and modify/remove arguments to suit you needs
Create datetime objects from relevant fields (use the strptime method of datetime class : create a date object from a string). Something like :
check_in = datetime.strptime(your_record[0]['check-in time'], '%Y-%m-%d')
check_out = datetime.strptime(your_record[0]['check-out time'], '%Y-%m-%d')
note: you need to adapt the format('%Y-%m-%d') to whatever format your DB returns
Compare both object with a simple expression :
if check_in < check_out:
...
else:
...
Do whatever other operations need to be done.
It's kinda hard to provide more info without additional details about your flow.
Hope this helps,
Cheers

How do I change the format ActiveRecord expects when parsing dates from a text field in a form?

The problem
I have a Ruby on Rails model with a Date attribute.
In the form for this model, I am using a single text field with a JQuery datepicker to represent this attribute (not a drop down for each of year, month, and day, as is the Rails custom).
The datepicker inserts dates with a mm/dd/yyyy format.
Rails is expecting dates with a dd/mm/yyyy format.
Examples
If a user selects March 12th, 2012, the datepicker puts 03/12/2012, which is interpreted by Rails as December 3rd, 2012.
If a user selects March 20th, 2012, the datepicker puts 03/20/2012, which is interpreted by Rails as the 3rd day of the 20th month of 2012. Since this date doesn't exist, Rails casts this to a nil value (I think).
Question
How do I change the date format Rails uses when parsing this date text field?
Notes:
1) I do not want to change the format of the date the datepicker inserts into the text field,
2) I am not asking about displaying my date attribute in a view.
I initially thought this could be solved through the Rails internationalization features, but it turns out I was wrong.
Ever since Ruby 1.9, the standard format for date parsing is dd/mm/yyyy, so as to better accomodate international users. More details can be found in this SO answer.
That standard is maintained in Rails, as Date.parse is now used to process data from form inputs. Using a before_validation callback won't work because the field is going to be received as nil by the callback method.
Right now there are two gems dealing with this specific issue, namely that date parsing in Rails does not follow the locale settings from I18n.locale. Both seem to work well.
delocalize, by clemens - Seems to have been applied successfully in a decent number or projects and has the highest number of stars at the moment.
i18n_alchemy by carlosantoniodasilva - This one has been released more recently. The author is a Rails core team member, and a very active one at that. Definitely deserves a look.
Since you don't want to change the picker's format, I would suggest you use a hidden field for the actual model property.
For example, add a hidden field for the model's date property, assuming you use a form builder as usual:
f.hidden_field :date
Then for the picker text input, don't bind it to the model's date property. Let's say the hidden field has ID 'modelname_date' and the picker text input has ID 'date_picker', use the following to make it work:
$(function(){
$("#date_picker").datepicker({altField: '#nodelname_date', altFormat: 'dd/mm/yyyy'});
});
In this way the date picker shows the date as 'mm/dd/yyyy' but Rails will see the date as 'dd/mm/yyyy'.
Update:
If you want to work this out on the Rails side, here's another solution I'd suggest:
Add a virtual property to your model: attr_accessor :bad_format_date
Add a before_validation callback in which you parse the input date and assign it to the real field:
before_validation do
self.date = Date.strptime(bad_format_date, "%m/%d/%Y")
end
Then for the form on the view use bad_format_date but initialize it with the date field value (if it's an edit form).
The timeliness gem makes ruby date/time parsing much more customizeable and integrates well with Rails.
Since you're working with Rails, be sure to check out the validates_timeliness project as well by the same guy. It includes all of timeliness plus sophisticated date/time validation methods for ActiveModel.
You could try do something like this.
$(function(){
$('#date_picker').datepicker( {
beforeShowDay: $.datepicker.noWeekends,
showOtherMonths: true,
selectOtherMonths: true,
dateFormat: 'dd-mm-yy',
defaultDate: date,
gotoCurrent: true
});
I just add the following monkey patch to config/time_formats.rb
class Date
class << self
alias :euro_parse :_parse
def _parse(str,comp=false)
str = str.to_s.strip
if str == ''
{}
elsif str =~ /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{2,4})/
year,month,day = $3.to_i,$1,$2
date,*rest = str.split(' ')
year += (year < 35 ? 2000 : 1900) if year < 100
euro_parse("#{year}-#{month}-#{day} #{rest.join(' ')}",comp)
else
euro_parse(str,comp)
end
end
end
end

How to update_attributes w/ UNIX Timestamp and set MySQL DATETIME automatically?

I just assumed that some rails magic would automatically convert an incoming post w/ a unix time 1345069440000 to the appropriate datetime on the backend. However, I have a model Event with a datetime called "start_at" and:
e = Event.new()
e.start_at = 1345069440000
e.save
It seems to send the 1345069440000 straight through and then mysql nulls it. Same with a ruby time
e = Event.new()
e.start_at = 1345069440
e.save
if I set it to some arbitrary strings, it does a better job of inferring:
e.start_at = '1/1344/12'
e.save
sets the date to '1334-12-01 00:00:00 UTC +00:00". So, it's making an attempt.
Clearly I can override the setter in my class, but I was hoping to change this behavior much higher up so that all controllers would support unix times for any datetime being passed up.
Rails 3.2, Ruby 1.9.2
Looks like this code from active_record/attribute_methods/time_zone_conversion.rb is attempting to do the conversion:
unless time.acts_like?(:time)
time = time.is_a?(String) ? Time.zone.parse(time) : time.to_time rescue time
end
One option (albeit a little heavy-handed) would be to monkey-patch Fixnum to add a .to_time method:
def to_time
Time.at(self)
end

How do I retrieve the locale-specific date format string in Flex / ActionScript 3?

How do I retrieve the locale-specific date format string in Flex / ActionScript 3? I am unable to find a method to return the actual format string (that which specifies the date format) based on the current locale. I am asking this question because I was hoping to find a way to convert a String to a Date based on the current SHORT date format for the locale. Java allows one to call:
DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT, locale)
to retrieve an instance of DateFormat that formats according to the SHORT format based on the locale.
Does similar functionality exist in Adobe Flex (ActionScript 3) 3? If not, is there a reliable third party library that exists for this?
I'm just found this package that do the job. Here describe the class DateTimeFormatter:
var formatter:DateTimeFormatter = new DateTimeFormatter(LocaleID.DEFAULT, DateTimeStyle.LONG, DateTimeStyle.SHORT);
var result:String = formatter.format(date);
Just cool.
Extending Gojan's answer:
private function cc(event:FlexEvent):void {
var formatter:DateTimeFormatter = new DateTimeFormatter(LocaleID.DEFAULT, DateTimeStyle.SHORT, DateTimeStyle.NONE);
//now if publishDate is a mx:DateField, the formatString of spark and mx components are slightly different.
//So, we replace all d with D and y with Y
publishDate.formatString=replaceAll(formatter.getDateTimePattern(), ["d", "y"], ["D", "Y"]);
}
private function replaceAll(text:String, searchArray:Array, replArray:Array):String {
for (var i:int=0; i<searchArray.length; i++) {
var s:String=searchArray[i];
var d:String=replArray[i];
text=text.split(s).join(d);
}
return text;
}
Yeah I have to say Java is better with dates - you set the locale and automatically your dates are outputted correctly! I can't seem to find such a facility in Flex.
In order to output your dates correctly for each locale I think you have to do what is written in this article: http://livedocs.adobe.com/flex/3/html/help.html?content=l10n_1.html. Maybe you should do this, and in the same class just make these strings which you've pulled from the locale file available to the rest of your app, then you'll be able to operate on them.
Otherwise perhaps this guy's library will help you? I'm not sure.
http://flexoop.com/2008/12/flex-date-utils-date-and-time-format-part-ii/