Change date field value while submitting the form in django - javascript

I have a form
forms.py
class RegistrationForm(BaseRegistrationForm):
name = forms.CharField(label='Name of the Entrepreneur', max_length=120)
ename = forms.CharField(label='Name of the Enterprise', max_length=120)
sector = forms.CharField(label='Industry Sector', max_length=50, widget=forms.Select(choices=zip(SECTOR_CHOICES, SECTOR_CHOICES)))
subsector = forms.CharField(label='Sub-sector', max_length=50, widget=forms.Select(choices=zip(SUBSECTOR_CHOICES, SUBSECTOR_CHOICES)))
address1 = forms.CharField(label='Address Line 1', max_length=100)
address2 = forms.CharField(label='Address Line 2', max_length=100, required=False)
city = forms.CharField(label='City/Town', max_length=50)
state = forms.CharField(label='State', max_length=50)
country = forms.CharField(label='Country', max_length=50)
postal_code = forms.CharField(label='Pin Code', max_length=10, required=False)
estd = forms.DateField(label='Establishment Details')
contact = forms.IntegerField(label='Contact Number')
For the DateField variable I have written javascript
JavaScript Code:
<script type="text/javascript">
$(function() {
$('#id_estd').datepicker( {
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'mm/yy',
onClose: function(dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1));
}
});
});
</script>
<style>
.ui-datepicker-calendar {
display: none;
}
</style>
In the estd field it shows mm/yy (ex: 02/2014)
While submitting the form I should submit the value like mm/dd/yy. So How can I change the value while submitting the form??

No use with the javascript or something else. There is a snippet in django use it.
https://djangosnippets.org/snippets/1688/
Save the snippet code in some file called widgets.py and import the class name in your forms.py file and follow the below code:
import datetime
class myForm(forms.Form):
# ...
date = forms.DateField(
required=False,
widget=MonthYearWidget(years=xrange(1990,datetime.date.today().year+1))
)
Hope it works.

It is a better idea to use one format for humans, and another alternate one for processing. JQuery UI Datepicker allows an alternate field to be populated with a different format: http://jqueryui.com/datepicker/#alt-field
Basically rename your existing datepicker field, add a hidden input named estd with an id id_estd (default name and id Django would assign) and add the following lines while initializing your datepicker:
altField: "#id_estd",
altFormat: "mm/dd/yy"

Why use javascript to change the value? Just set the format in django.
class MyForm(Form):
# the default format is %Y-%m-%d
estd = forms.DateField(
widget=forms.widgets.DateInput(format="%m/%Y")
)
Docs for the DateInput widget; https://docs.djangoproject.com/en/1.7/ref/forms/widgets/#dateinput
Date/Time input format settings are detailed here; https://docs.djangoproject.com/en/1.7/ref/settings/#date-input-formats

Related

JQuery datepicker language not working correctly

I using jquery datepickers in my project and need to have local language on it.
I need to pass language from back end via gon.locale(rails stuff)
So here is my ts code
const search_legs_1_datepicker = $("#search_legs_1_datepicker");
var leg_1_datepicker = $("#search_legs_1_datepicker").datepicker({
language: gon.locale,
classes: 'inline-picker',
altField: '#search_legs_1_date',
defaultDate: new Date(search_legs_1_datepicker.attr("data-defaultDate")),
minDate: new Date(search_legs_1_datepicker.attr('data-mindate')),
maxDate: new Date(search_legs_1_datepicker.attr('data-maxdate')),
altFormat: 'yy-mm-dd',
onSelect: (formattedDate, date, inst) => {
if ($("#search_legs_1_hotel_date").length > 0) {
$('#search_legs_0_hotel_date').datepicker().data('datepicker').update('maxDate', date);
$('#search_legs_1_hotel_date').datepicker().data('datepicker').update('maxDate', date);
$('#search_legs_1_hotel_date').datepicker().data('datepicker').datepicker("setDate", date);
}
}
})
I checked gon.locale with console and get sv-SE so it's pass language.
Also I try to do it like this
language:"sv-SE"
It not works too.
But for some reasons I have en at my datepickers.
Where is my problem?
Check that you have the language file.
Datepicker provides support for localizing its content to cater for
different languages and date formats. Each localization is contained
within its own file with the language code appended to the name, e.g.,
jquery.ui.datepicker-fr.js for French. The desired localization file
should be included after the main datepicker code. Each localization
file adds its options to the set of available localizations and
automatically applies them as defaults for all instances.
http://api.jqueryui.com/datepicker/
Localization files can be found there : https://github.com/jquery/jquery-ui/tree/master/ui/i18n
You need to include language file and then set the default language as "sv".
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>
Date Picker on input field: <input type="text" id="search_legs_1_datepicker" name="date1"/>
const search_legs_1_datepicker = $("#search_legs_1_datepicker");
var leg_1_datepicker = $("#search_legs_1_datepicker").datepicker({
//language: gon.locale,
classes: 'inline-picker',
altField: '#search_legs_1_date',
defaultDate: new Date(search_legs_1_datepicker.attr("data-defaultDate")),
minDate: new Date(search_legs_1_datepicker.attr('data-mindate')),
maxDate: new Date(search_legs_1_datepicker.attr('data-maxdate')),
altFormat: 'yy-mm-dd',
onSelect: (formattedDate, date, inst) => {
if ($("#search_legs_1_hotel_date").length > 0) {
$('#search_legs_0_hotel_date').datepicker().data('datepicker').update('maxDate', date);
$('#search_legs_1_hotel_date').datepicker().data('datepicker').update('maxDate', date);
$('#search_legs_1_hotel_date').datepicker().data('datepicker').datepicker("setDate", date);
}
}
})
$.datepicker.setDefaults($.datepicker.regional['sv']);
This file supports all languages - "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"
If you want to include specific file then get the specific langauge file from here https://github.com/jquery/jquery-ui/tree/master/ui/i18n.

Changing the format of date after picking from datepicker after SAPUI5

I have a datepicker from which I want to extract the date and display in a label. Currently the date is getting displayed in the format MM/DD/YYYY but I want it in the format MMM dd, yyyy (Nov 17, 2017). Below is the code :
screenDate=view.byId("screeningDate").getValue();
var date = view.byId("__date");
date.setText(screenDate);
XML :
<HBox alignItems="Center" renderType="Bare">
<Label text="Date of Screening" width="50%"/>
<DatePicker class="sapUiLargeMarginBegin" width="50%" id="screeningDate"/>
</HBox>
In addition to Naveen's answer here's the solution with your existing code:
screenDate=view.byId("screeningDate").getValue();
var date = view.byId("__date");
// Make date object out of screenDate
var dateObject = new Date(screenDate);
// SAPUI5 date formatter
var dateFormat = sap.ui.core.format.DateFormat.getDateInstance({pattern : "MMM dd,YYYY" });
// Format the date
var dateFormatted = dateFormat.format(dateObject);
date.setText(dateFormatted);
FYI, By getting view controls and updating the property in it is not good. It will be good if you have a model.
Solution for your problem is below,
<Label text="{
path: '/date',
type: 'sap.ui.model.type.Date',
formatOptions: {
style: 'medium',
pattern: 'MMM dd, yyyy'
}}"/>
<DatePicker dateValue="{/date}"/>
And in the controller I have a JSONModel as below,
onInit : function() {
this.model = new JSONModel({
date : new Date(0)
});
this.getView().setModel(this.model);
}

pickadate.js set focus depending on first input

I am using pickadate.js for arrival & departure dates and would like the departure date to disallow any date on or before the arrival date and set the departure date to focus on the date after the arrival date. Thus an arrival on, say, 16th December 2016 would permit a departure date only from 17th Dec to be selected. This is what I have:
<script src="pickadate/lib/jquery.js"></script>
<script src="pickadate/lib/picker.js"></script>
<script src="pickadate/lib/picker.date.js"></script>
<script src="pickadate/lib/legacy.js"></script>
<script type="text/javascript">
$('#dateArrival').pickadate({
min: true,
max: new Date(2018,12,31),
format: 'd mmm yyyy', // Friendly format displayed to user
formatSubmit: 'yyyy-mm-dd', // Actual format used by application
hiddenName: true, // Allows two different formats
disable: [ // Dates already booked
new Date(2016,11,13),
new Date(2016,11,29)
]
});
$('#dateDepart').pickadate({
min: true,
max: new Date(2018,12,31),
format: 'd mmm yyyy',
formatSubmit: 'yyyy-mm-dd',
hiddenName: true,
disable: [
new Date(2016,11,13),
new Date(2016,11,29)
]
});
</script>
var frompic = $('#input_from').pickadate();
var topic = $('#input_to').pickadate();
After initialization , retrieve picker objects
fromIns = frompic.pickadate('picker');
toIns = topic.pickadate('picker');
Add set event handler
fromIns.on('set', function(event) {
if ( event.select ) {
sel = fromIns.get('select'); //get entered date
newDte = new Date( sel.year,sel.month,sel.date ) ;
newDte.setDate(newDte.getDate()+1); // inc date by 1
toIns.set('min', new Date( newDte.getFullYear(),newDte.getMonth(),newDte.getDate()));
}
});

Replacing two variables after filling a form

I'm not much of a Javascript expert, but sometimes I need to turn to it.
I have a script which allows the user to choose two dates (from and to) to create a report.
<div onmouseover="myFunction()">
<input id="id_from_date" name="from_date" type="text">
<input id="id_to_date" name="to_date" type="text">
</div>
<script>
function myFunction() {
$('#id_from_date').datetimepicker({
format: 'd-m-Y',
lang: 'pl',
pickTime: false,
timepicker: false,
weeks: true,
dayOfWeekStart: 1,
closeOnDateSelect: true
});
$('#id_to_date').datetimepicker({
format: 'd-m-Y',
lang: 'pl',
pickTime: false,
timepicker: false,
weeks: true,
dayOfWeekStart: 1,
closeOnDateSelect: true
});
var from = document.getElementById("id_from_date").value;
var to = document.getElementById("id_to_date").value;
var url = '{% url 'logistyka_tabela_brakow.views.report_from_to' '11-11-1111' '12-12-1212' %}';
document.getElementById("link").setAttribute("href", url.replace(/11-11-1111/, from), url.replace(/12-12-1212/, to))
}
</script>
<a id="link" type="button" class="btn btn-success">go!</a>
I'm at the end of my tether here. The code replaces the first variable, id_from_date, with the date a user chooses. Unfortunately, it ignores the second variable, id_to_date. Can anyone please give me a hint why it happens so?
I cannot leave var url withour any initial values, because the application crashes without anything given while opening the view.
The whole project is created in Django and the view for the report is:
def report_from_to(request, from_date, to_date):
from datetime import datetime
strfrom = datetime.strptime(from_date, "%d-%m-%Y")
strto = datetime.strptime(to_date, "%d-%m-%Y")
report = Braki.objects.filter(Q(date__gte=strfrom), Q(date__lte=strto))
return render(request, 'logistyka_tabela_brakow/report_from_to.html', {'report': report})
the form:
class ReportForm(forms.Form):
from_date = forms.DateField()
to_date = forms.DateField()
fields = '__all__'
the url is obviously:
url(r'report_from_to/(?P<from_date>[0-9]{2}-[0-9]{2}-[0-9]{4})/(?P<to_date>[0-9]{2}-[0-9]{2}-[0-9]{4})',
'logistyka_tabela_brakow.views.report_from_to', name='report_from_to'),
The syntax of setAttribute is
element.setAttribute(name, value);
You are calling it with 3 arguments, so the third one gets ignored.
document.getElementById("link")
.setAttribute("href",
url.replace(/11-11-1111/, from),
url.replace(/12-12-1212/, to)
);
This should do it
var url = '{% url 'logistyka_tabela_brakow.views.report_from_to' '11-11-1111' '12-12-1212' %}';
url = url.replace(/11-11-1111/, from);
url = url.replace(/12-12-1212/, to);
document.getElementById("link").setAttribute("href", url);

How to extract only the months from the datepicker widget in Kendo UI to an alertbox?

I am currently working on an ASP.NET MVC 4 project, in my view I am using Kendo UI. I want to display only the month and year from the Datepicker widget(Example: JANUARY 2016) into the alertbox, but instead I am getting the following:IMAGE
My view code is as follows:
#(Html.Kendo().DatePicker()
.Name("datepicker")
.Start(CalendarView.Year)
.Depth(CalendarView.Year)
.Format("MMMM yyyy")
.Value(DateTime.Today)
.HtmlAttributes(new { style = " width: 95.5%;})
.Events(e => e.Change("monthpicker_change"))
)
<script>
// monthpicker_change function
function monthpicker_change() {
var month = $("#datepicker").data("kendoDatePicker");
alert(month.value());
}
</script>
Please suggest me what changes I need to do in my script, in order to display only the selected Month and Year in an Alert box.
PS: I have formatted the datepicker to display only the MONTHS and YEAR, not the standard dates
kendoDatePicker.value method always return javascript Date.
You should use Date methods to extract month and year from date object:
var date = $("#datepicker").data("kendoDatePicker").value();
alert((date.getMonth()+1) + '.' + date.getFullYear());
Beware: getMonth() return values from 0 to 11; 0 is january.
Here is full reference of Date functions: http://www.w3schools.com/jsref/jsref_obj_date.asp

Categories