I have a model field called close_date
models.py
class Project(models.Model):
close_date = models.DateTimeField(blank=True, null=True)
In my forms, I don't do add any classes to display this because I will do it in my template using django-widget-tweaks. However, my forms look like this:
forms.py
class NewProjectForm (ModelForm):
class Meta:
model = Project
fields = ['close_date', ...]
templates
{% load widget_tweaks %}
<div class="form-group" id="close_date">
<label>{{project_form.close_date.label}}</label>
<div class="input-group date">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
{% render_field project_form.close_date class="form-control" type="text" %}
</div>
</div>
<script>
$('#close_date .input-group.date').datepicker({
todayBtn: "linked",
keyboardNavigation: false,
forceParse: false,
calendarWeeks: true,
autoclose: true
});
</script>
All this works fine, I can display the form, save it to the database and even display data to the user, but when I want to edit the this object and I populate the form from my views, I see this in the datepicker input field:
2018-02-28 00:00:00
How can I change what is displayed there from 2018-02-28 00:00:00 to 02/28/2018?
Is that on the django side of things or the JS side?
Have you tried specifying the input format in your form, like so?
close_date = DateField(input_formats=['%m/%d/%Y'], label=_('Installation Date'),widget=DateInput())
You should use a DateField(doc link) instead of a DateTimeField inside your model :)
I can give you a partial solution as it is 3 am in the morning (sorry). Use a DateField instead of a DateTimeField so that the 00:00:00 part is not there anymore.
Next, you need to reformat the date from 2018-02-28 to 02/28/2018. That's it. From what I understand, either input will work with the form, but during editing the one with the - is preferred by Django so that's what it shows you.
If this bothers you then either use a JS library to put a calendar so that users use a calendar to input/change the data rather than type it by hand, or use a custom javascript code to change the input after the whole page loads.
Related
I am using django-bootstrap-datepicker-plus package, and I am trying to display an alert when the date is changed. However, jquery does not seem to detect any changes to the date.
Following this question Detect change to selected date with bootstrap-datepicker only works when I add the JQuery UI CDN to my code, which causes a problem as two datepickers appear. Is there a way to get JQuery to detect a change in django-bootstrap-datepicker without adding JQuery UI code?
forms.py
from django import forms
from bootstrap_datepicker_plus.widgets import DatePickerInput
class ExampleForm(forms.Form):
DOB = forms.DateField(required=False, label="Date of Birth",
input_formats=['%d/%m/%Y'],
widget=DatePickerInput(format='%d/%m/%Y')
)
Html
<div class="col-12 col-md-6 mb-0 p-1">
{{ form.DOB|as_crispy_field }}
</div>
Rendered HTML
There is a lot of JS packages with similar [date,time]picker functionality. django-bootstrap-datepicker-plus uses eonasdan picker, according to the docs. They use different event names. Eonasdan implementation prefixes all events with dp. namespace, as stated here, so the following should work:
$('#id_DOB').on('dp.change', ev => myHandler(ev));
I'm constructing a view where the user can edit the date of each item for the model Store and I'm using JqueryUI datepicker JS.
This is the view (extract):
#model IEnumerable<Application.Models.Store>
#foreach (var item in Model)
{
<input type="text" class="datepicker form-control" asp-for="#item.DesignatedDate"
name="DesignatedDate" form="#(String.Format("{0}{1}","form",item.StoreID))" />
and this is the JS:
<script>
$(function () {
$(".datepicker").datepicker();
});
</script>
Since I'm showing multiple Stores in this grid, each one has it's own date to be picked.
The problem I'm having is that all the datepickers are linked between each other since each input has:
asp-for="#item.DesignatedDate"
which translates to:
id="item_DesignatedDate"
Note: I use asp-for="#item.DesignatedDate" in order to show the current date that the Store has registered when the pages loads.
And so, when I change the date of any Store, it will change the date of the first Store, always.
Any idea on how to fix this?
Thanks in advance!
Solved.
I just had to add an id to each in order to be differentiated:
id="#(String.Format("{0}{1}","any",item.StoreID))"
And now it works.
I am trying to use angular-bootstrap datepicker module in my app and encountered small problem. I use input text and button for displaying date like this:
<div class="row" id="datePicker">
<p class="input-group">
<input type="text" class="form-control" datepicker-popup="{{format}}" ng-model="currentDate"
is-open="opened" datepicker-options="dateOptions" date-disabled="disableDt(date, mode)"
ng-required="true" close-text="Close" show-button-bar="false" ng-init="" readonly/>
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open($event)">
<i class="glyphicon glyphicon-calendar"></i>
</button>
</span>
</p>
</div>
And due to using angular google maps I have to manually bootstrap my app. It seems that due to manual bootstrapping, datepicker is unable to properly format the date and displays whole unformatted date. As I choose any date from datepicker, date is then displayed correctly in the input field. What is more, model changes don't force format to change (e.g. initially I got some dates from json file and they were displayed in the field, but without formatting too).
Example below:
Initial date: Fri Jan 17 2014 01:00:00 GMT+0100 (CET)
Expected date (and one displayed after choosing the same day): 17 January 2014
Is there any way of refreshing this widget so it knows proper formatting at the beginning or changing it at the proper moment to initialize properly?
EDIT: As I moved datepicker to fragment, it should not have problems with not initialized model (this fragment is loaded later). Still, problem occur - date is not formatted and seems not to be connected with formatter or model at all (e.g. making format dropdown and choosing different values as in tutorial doesn't work until date is chosen inside datepicker).
EDIT 2 Solution from the link provided by camden_kid worked! :) Details in his comment.
Answer could be found here:
AngularJS 1.3 - Datepicker initial format is incorrect
I manually formatted the date on initialization as below:
$scope.currentDate = $filter('date')(new Date(), $scope.format);
However, better solution would be to overload directive as follows (taken from the original link):
angular.module('myApp').directive('datepickerPopup', function (dateFilter, datepickerPopupConfig) {
return {
restrict: 'A',
priority: 1,
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
var dateFormat = attr.datepickerPopup || datepickerPopupConfig.datepickerPopup;
ngModel.$formatters.push(function (value) {
return dateFilter(value, dateFormat);
});
}
};
});
When date was changed by datepicker afterwards, datepicker itself handled any date formatting :)
Thanks to #camden_kid for providing the link! :)
i'm new to symfony, and don't know much about javascript!
i created a symfony form, and added a UniqueEntity constraint on the name and firstname, so it's not possible to add a same person twice in the database.
#UniqueEntity(fields={"firstname","name"}, message="this person already exists")
it works pretty well!
but in this case, i would like symfony to show me a javascript window with a message and 2 choices. for example: "joe smiley already exists! would you like to add an homonym? yes / no
does anyone know how to do this?
Much thanks
No, this validation is strictly server-side.
You should try some JS validation libraries like: http://rickharrison.github.io/validate.js/ (just an example)
well you could try to find if is there and error message for that field, and that will depend on how are you displaying your form fields, i strongly strongly recommend you to customize your form rendering to suit your needs, here is and example of what can you do.
<div class="control-group {% if(form_errors(form.descripcion)|length) %} error {% endif %} ">
{{ form_label(form.descripcion, null, { 'label_attr': {'class': 'control-label'} }) }}
<div class="controls">
{{ form_widget(form.descripcion) }}
{{ form_errors(form.descripcion) }}
</div>
</div>
that will render this when the validation shows and error message
<div class="control-group error ">
<label class="control-label required" for="AreaComercio_descripcion">Descripcion</label>
<div class="controls">
<input type="text" id="AreaComercio_descripcion" name="AreaComercio[descripcion]" required="required" >
<span class="help-inline">This value should not be blank.</span>
</div>
</div>
so you have to ask if is there an span sibling with the class help-inline if you dont know how to custimze your form rendering take a look at this and another advice use jquery, there are lots of people using it, jquery have an strong comunity that will help you if you are in the need, that said, i will use jquery to ilustrate what you can do to solve your problem.
if($("#AreaComercio_descripcion ~ .help-inline").length) { // here using sibling selector filter to ask if there a siblig with the class help-inline
var invalid_value = $("#AreaComercio_descripcion").val(); // asking for the field value thru its id attribute
confirm(invalid_value+" already exists! would you like to add an homonym ?");
}
using javascript confirm is the easiest way to do what you want but you can use other more flexible options like jquery dialog or you could try to install twitter bootstrap in your symfony installation, well i guess thats all i hope it will be usefull to you
Currently I'm using bootstrap datetimepicker which allows user to select date.
But when I run it in different laptops i get different format for the date.
For example in my laptop when i run the app and check the value that is being passed in my post method i get something like this
8/27/2013 12:00:00 AM
but when i run the app in someone else's laptop i get this value in the post method
1-1-0001 00:00:00
this results to invalid modelstate in my controller's post method.
I have no idea why this is happening. Can someone give me some suggestion and how can I solve this issue and make the datetime format always look like 8/27/2013 12:00:00 AM post method?
Here is the code in view
<div id="datetimepicker2" class="input-append date">
<input name="DateEntered" type="text"/>
<span class="add-on">
<i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
</span>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#datetimepicker2').datetimepicker({
language: 'en',
pick12HourFormat: true
});
});
</script>
'Try setting the format for the datetimepicker explicitly:
<script type="text/javascript">
$(document).ready(function() {
$('#datetimepicker2').datetimepicker({
language: 'en',
pick12HourFormat: true,
format: 'MM/dd/yyyy hh:mm:ss'
});
});
</script>
UPDATE
Try tagging the view model property or action method argument with the DisplayFormat attribute:
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy hh:mm:ss}")]