How can I keep updated a current date in form field? I've tried to set date at views.py and forms.py, but in that case it saves date in cache only once (when I update index.wsgi) and then it's don't update date on every page reloads. Daily restart of the app is not an option. I can't believe javascript is the only way. I'm just stuck on it, help me, please.
How it looks like now: I have a form:
class AddRecordForm(forms.ModelForm):
class Meta:
model = Journal
fields = ['date']
widgets = {
'date': forms.DateInput(attrs={'type': 'date', 'class': 'form_input', 'value': date.today().strftime("%Y-%m-%d")}),
From this model:
class Journal(models.Model):
date = models.DateTimeField()
And resulting html:
<input type="date" name="date" class="form_input" value="2020-01-17" required="" id="id_date">
Looks good, but if I go to the page tomorrow it will still be 2020-01-17. But it should be 2020-01-18 and so on. Date in form updates only after app reload (touch index.wsgi).
UPD: As it turned out, frontend way is only way. Have solved the issue in JS:
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day) ;
$("#id_date").val(today);
You'll need to use a frontend component
i.e A Date/Time picker as opposed to setting the value on the backend since by the time the template is rendered that date/time becomes invalid (In your case the next day).
form.py
class AddRecordForm(forms.ModelForm):
date = forms.DateTimeField(
input_formats=['%d/%m/%Y %H:%M'],
widget=forms.DateInput(
attrs={
'type': 'date',
'class': 'form_input',
},
),
)
class Meta:
model = Journal
fields = ['date']
form.html
{{ form.date.id_for_label }}
<script>
$(function () {
$("#{{ form.date.id_for_label }}").datetimepicker({
format: 'd/m/Y H:i',
});
});
</script>
Related
I'm using version 6 of Tempus Dominus, whose documentation is found at https://getdatepicker.com/6/.
My question is:
How do I set the date format?
I have this HTML control:
<div class="col-auto">
<label for="fromDateInput">From date:</label>
<div class="input-group" id="fromDate" data-td-target-input="nearest" data-td-target-toggle="nearest">
<input id="fromDateInput" type="text" class="form-control" data-td-target="#fromDate">
<span class="input-group-text" data-td-target="#fromDate" data-td-toggle="datetimepicker"><span class="fa-solid fa-calendar"></span></span>
</div>
</div>
And I have the following JavaScript configuration of the Tempus Dominus datepicker control:
const picker = new tempusDominus.TempusDominus(document.getElementById('fromDate'), {
display: {
components: {
clock: false
}
},
localization: {
startOfTheWeek: 1
}
});
In the browser, the control looks like this:
I then select a date:
As you can see in the field, the date is written as 06/22/2022. However, I would like the format to be YYYY-MM-DD, such that the date in this instance becomes 2022-06-22. How do I achieve that?
I found documentation for it on the plugins overview page: https://getdatepicker.com/6/plugins/
It has the following example:
Per Picker
It is possible to use this system per picker. For instance:
const td = new tempusDominus.TempusDominus(document.getElementById('datetimepicker1'));
td.dates.formatInput = function(date) { {return moment(date).format('MM/DD/YYYY') } }
The code above would affect a single picker but not globally. You could easily adapt this code to have a common formatting function taking in a format string.
So I adapted my code in the following way:
const picker = new tempusDominus.TempusDominus(document.getElementById('fromDate'), {
display: {
components: {
clock: false
}
},
localization: {
startOfTheWeek: 1
}
});
picker.dates.formatInput = date => moment(date).format('YYYY-MM-DD')
And now the date format looks like I want it:
As you can see, the date is now written 2022-06-22.
And in case you don't want to use moment.js…
const picker = new tempusDominus.TempusDominus(document.getElementById('fromDate'), {});
picker.dates.formatInput = date =>
date.getFullYear() + '-' +
("0"+(date.getMonth() + 1)).slice(-2) + "-" +
("0" + date.getDate()).slice(-2);
After submit form, correct format changes to default format.
if using jquery, and your plugin is >= 6.2.7.
load the plugins customDateFormat.js
set your tempusDominus to extend custom format
tempusDominus.extend(window.tempusDominus.plugins.customDateFormat);
Complete code like
tempusDominus.extend(window.tempusDominus.plugins.customDateFormat);
$('#fromDate').tempusDominus({
localization: {
format: 'yyyy-MM-dd',
}
});
Reference:
https://getdatepicker.com/6/plugins/customDateFormat.html
In my VueJS application I have a component with a form.
In that form I have a field to pick the date.
My requirement is to show an error message if the selected date is older than the current date.
Basically the selected date need to be either today's date or future date.
I'm using Moment JS.
I have following custom rule in my Validator.vue
const dateIsToday = (value) => {
var todayDate = moment(new Date()).format("DD-MM-YYYY");
var selectedDate = value;
return selectedDate>=todayDate;
};
But this works only if I selected an old date from the current month... Assume if the user has picked an older date from this month like 10-04-2022, then it'll show the error message.
But if the user selected an old date from last month or a past month like 10-01-2022, this won't show me the error message....
In my form.vue I have
<div class="w-1/2 mr-2">
<p class="text-certstyle-titles font-bold text-sm mb-1">Start date</p>
<div class="h-12">
<cs-date-picker
id="startDate"
v-model="project.start_date"
:default-selection="true"
:name="`${identifier}-start_at`">
</cs-date-picker>
<validator
:identifier="`${identifier}-validate-project`"
:rules="validations.startDate"
:name="`${identifier}-start_at`"
/>
</div>
</div>
And under my validations I have,
startDate: {
required: {
message: 'Project Start date is required.'
},
dateIsToday: {
message: 'Date has to be today's date or a future date.'
},
},
It seems that you are comparing strings. Instead you should make real use of moment and compare moment dates:
const dateIsToday = (value) => {
let todayDate = moment();
let selectedDate = moment(value, "DD-MM-YYYY");
return selectedDate.isSameOrAfter(todayDate);
};
How can I hide the calendar after a date is selected? I am using Date-time-picker by DanyelYKPan.
Is there a specific function that I can use? My code below
<div class="col-3">
<div class="form-group calenderForm calenderForm1">
<label for="templateName">REPAIR DATE (FROM)</label>
<owl-date-time name="repairDateFrom"
[(ngModel)]="repairDateFrom"
[max]="max"
[type]="'calendar'"
[dateFormat]="'YYYY-MM-DD'"
[placeHolder]="'YYYY-MM-DD'"
></owl-date-time>
<div class="error-message-block"></div>
<input type="hidden" name="repairDateFrom" id = "repairDateFrom" value="
{{repairDateFrom | date: 'yyyy-MM-dd'}}" (click)="closeDatePopUp()"/>
</div>
</div>
From top of the code through picker plugin component call will goes to below function.
DateTimePickerComponent.prototype.updateFormattedValue = function () {
var formattedValue = '';
if (this.value) {
var d = new Date();
if (this.isSingleSelection()) {
this.value = this.value.setHours(d.getHours(), d.getMinutes());
formattedValue = date_fns_1.format(this.value, this.dateFormat,
{ locale: this.locale.dateFns });
$('.owl-calendar-wrapper').on('click',function(){
$('.owl-dateTime-dialog').hide();
});
}}}
I tried with above code it will works only one time after clicking on date field second time date popup will not come.
Please help me to solve this problem.
If I were you I would use the mechanism of Parent call of #ViewChild described in the angular Component Interaction page.
1 - import the DateTimePickerComponent
import { DateTimePickerComponent } from "ng-pick-datetime/picker.component"
2- Refer it to ViewChild and assign a variable name:
#ViewChild(DateTimePickerComponent) picker: DateTimePickerComponent;
3- Now you can access all non private attribute/method described here: https://github.com/DanielYKPan/date-time-picker/blob/master/src/picker.component.ts by this.picker
For hiding the calendar you can set the dialogVisible to false:
this.picker.dialogVisible = false
Now time to detect the click event in our calendar. The simplest way is to use (ngModelChange) event.
<owl-date-time
[(ngModel)]="repairDateFrom" name="repairDateFrom"
(ngModelChange)="onDateChange()"
[type]="'calendar'"
[dateFormat]="'YYYY-MM-DD'"
></owl-date-time>
And in our component :
onDateChange() {
this.picker.dialogVisible = false;
}
I am using angular material (md-datepicker). My requirement is to set different date format based on selection. i.e. if user select 'daily', datepicker would show 'MM/DD/YYYY'. If user select 'monthly' then datepicker should show 'MMM YYYY' and for 'hourly', it should be 'MM/DD/YYYY hh:mm'
https://plnkr.co/edit/S4mnF7?p=preview
Is it feasible using md-datepicker? I do not see any option to set format property in HTML. Saw the documentation of $mdDateLocaleProvider. But it does not give option to set different format to different controls.
You can use $mdDateLocaleProvider , the formatDate function to set the date format: Function to format a date object to a string. The datepicker directive also provides the time zone, if it was specified.
And in the datepicker directive, you can use the md-date-locale attribute: This Allows for the values from the $mdDateLocaleProvider to be ovewritten on a per-element basis (e.g. msgOpenCalendar can be overwritten with md-date-locale="{ msgOpenCalendar: 'Open a special calendar' }").
something like:
<md-datepicker ng-model="myDate" md-date-locale="mylocale"></md-datepicker>
<md-datepicker ng-model="myOtherDate" md-date-locale="myOtherlocale"></md-datepicker>
and in controller
$scope.mylocale = {
formatDate: function(date) {
var m = moment(date);
return m.isValid() ? m.format('YYYY') : '';
}
};
$scope.myOtherlocale = {
formatDate: function(date) {
var m = moment(date);
return m.isValid() ? m.format('MMMM YYYY') : '';
}
};
https://embed.plnkr.co/u9wY3rvtpmXdQ7zrbMpB/
I'd like to preface this saying I know very little JavaScript.
I have a Bootstrap datepicker using a date range, picked up from eternicode.
My goal is to select a day in startDate and then have the days available to endDate only be on or after startDate and within startDate's financial year.
Examples:
If I chose Oct 1st 2016, the endDate should cap out at Sep 30th 2017
If I chose Jan 12th 2017, the endDate should cap out at Sep 30th 2017
If I chose Sep 30th 2017, the endDate should also be Sep 30th 2017
Pretty much, if the startDate month is in [Oct, Nov, Dec] then
endDate caps out at Sep 30th (startDate year + 1) else endDate caps
out at Sep 30th (startDate year)
In my reportWebpage.cshtml file I have:
<div class="col-md-2">
Date Range:
</div>
<div class="col-md-5" id="dateRangeContainer">
<div class="input-daterange input-group" id="datepicker">
#Html.TextBox("startDate", "", new { #class = "input-sm form-control", name= "startDate" })
<span class="input-group-addon">to</span>
#Html.TextBox("endDate", "", new { #class = "input-sm form-control", name = "endDate" })
</div>
</div>
In my related.js I have a very basic datepicker setup:
$(function () {
$('#dateRangeContainer .input-daterange').datepicker({
autoclose: true,
todayBtn: "linked",
clearBtn: true
});
});
I know there is a datesDisable property I can set, and while it's functionality is what I want it seems to be based off an array of dates which seems like the wrong idea here.
As a test, I replaced the datapicker js code above with what is shown below.
Like in this SO Answer I've tried adding an onSelect property to just the #startDate datepicker, but I'm not getting a response from the alert embedded, nor is Google Chrome's Dev Tools hitting the debug point placed on it:
$('#startDate').datepicker({
onSelect: function() {
var date = $(this).datepicker('getDate'),
day = date.getDate(),
month = date.getMonth() + 1, // Offset the zero index to match normal month indexes
year = date.getFullYear();
alert(day + '-' + month + '-' + year);
}
});
I was hoping that by doing that I could at least start building some if else loops or something.
I'm struggling to figure out how to even start with this problem, so any help or suggestions will be very much appreciated!
Edit 1:
I figured out that trying to disable a huge range of dates was the wrong way to view this problem, and that I should instead focus on utilizing the setStartDate and setEndDate properties.
Using some combined tips from these SO answers:
Bootstrap datepicker change minDate/startDate from another datepicker
Print Var in JsFiddle (This was mostly just a helper, giving credit where credit is due)
I mashed together this JSFiddle: http://jsfiddle.net/wsodjsyv/203/
Where it currently is, it does it's job of restricting to the proper financial year. I just need to tweak it so that when I clear End Date I'm able to move Start Date past that point again. Right now it'll require a refresh if I determine I want to move Start Date past Sept. 30 (whatever year got chosen)
Here is my new related.js file pertaining to the date picker; with this code I am able to restrict the date range to Start Date's fiscal year:
$(function () {
// Ranged datepickers
$('#dateRangeContainer .input-daterange').datepicker({
autoclose: true,
todayBtn: "linked",
clearBtn: true
});
$('#startDate').datepicker().on('changeDate', function(selected) {
var endDate_Bottom = null;
var endDate_Cap = null;
if (selected.date != null) {
endDate_Bottom = new Date(selected.date.valueOf());
endDate_Cap = new Date(selected.date.valueOf());
if (endDate_Bottom.getMonth() >= 9 && endDate_Bottom.getMonth() <= 11) {
endDate_Cap = new Date(endDate_Bottom.getFullYear() + 1, 8, 30);
} else {
endDate_Cap = new Date(endDate_Bottom.getFullYear(), 8, 30);
}
}
$('#endDate').datepicker('setStartDate', endDate_Bottom);
$('#endDate').datepicker('setEndDate', endDate_Cap);
});
$("#endDate").datepicker().on('changeDate', function(selected) {
var startDate_Cap = null;
if (selected.date != null) {
startDate_Cap = new Date(selected.date.valueOf());
}
$('#startDate').datepicker('setEndDate', startDate_Cap);
}).on('clearDate', function(selected) {
var startDate_Cap = null;
$('#startDate').datepicker('setEndDate', startDate_Cap);
});
});
I've added some checks for when the date is null to avoid the console log being filled with errors when .valueOf() is called on an empty date.
I also brought back the dateRangeContainer block to handle the repeated options and to allow for the styling that highlights the date range selected in the calendar.