I would like to use the included Django DateTimeInput widget as a datetimepicker on my website. No matter what I try however, the widget returns a datetime value in an incorrect format which will not send to my database.
I need the format '%Y-%m-%d %H:%M:%S', but the widget returns '%d/%m/%Y %H:%M:%S'
This problem has been discussed a tad here:
http://stackoverflow.com/a/35968816/1382297
I believe the problem may be from setting the input_type to DateTime-local, but I don't know other options and cannot find any in the documentation. I've tried passing format='%Y-%m-%d %H:%M:%S' to the widget, as well as FORMAT_INPUTS = ['%Y-%m-%d %H:%M:%S'], and tried initializing these in the DateInput class, all with no luck.
Here is my forms.py
class DateTimeInput(forms.DateTimeInput):
input_type = 'datetime-local'
class EnterMatchForm(forms.ModelForm):
class Meta:
model = match
fields = ('match_name', 'player1', 'player2', 'victory', 'match_description', 'match_date')
widgets = {
'match_date': DateTimeInput(),
}
What is the right way to set up the widget so that it returns datetime values in the format Y-m-d H:M:S? Thanks in advance!
You have to pass input_formats not formats or FORMAT_INPUTS.
https://docs.djangoproject.com/en/3.0/ref/forms/fields/#datetimefield
Related
I've a model which have a DateField.
class A(model.Model):
a = model.DateField()
class SerializerA(serializers.ModelSerializer):
class Meta:
model = A
fields = (a,)
The payload that I pass have a chance that it might send only year, for eg:-
{
"a": "1991"
}
It returns an error saying,
"Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]."
I'm already passing one the format, as mentioned in the error, but still I'm getting an error.
Why?
One of the simple solutions will be, define field a as separate in your serializer and provide sufficient values to the input_formats argument
required_formats = ['%Y', '%d-%m-%Y'] # add other formats you need
class SerializerA(serializers.ModelSerializer):
a = serializers.DateField(input_formats=required_formats)
class Meta:
model = A
fields = ('a',)
You need to set all needed date formats to variable DATE_INPUT_FORMATS in settings.py, for example:
DATE_INPUT_FORMATS = ['%d-%m-%Y']
I'm unable to validate datetime field. Is there something I missed?
from django import forms
class A(forms.Form):
a = forms.DateTimeField(widget=forms.DateTimeInput(format=('%Y-%m-%dT%H:%M')))
data = {'a':"2007-03-04T21:08"}
a = A(data)
print a.is_valid()
-> False
print a.errors
-> {'a': [u'Enter a valid date/time.']}
solution:
class A(forms.Form):
a = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M'])
You've specified the format parameter to the widget, which describes how the existing value should be displayed. You need to provide the input_formats parameter to the field itself, which determines how the data is accepted.
I'm trying to set the format of a DateInput to SHORT_DATE_FORMAT. However, the following code does not work work.
forms.py
from django.conf.global_settings import SHORT_DATE_FORMAT
class EventForm(ModelForm):
# ...
startDate = forms.DateField(
widget=forms.DateInput(
format=SHORT_DATE_FORMAT
)
)
In the views.py, an example entry is read from the database and a form is created using form = EventForm(instance=event1). The template then shows that widget using {{form.startDate}}. The input shows up correctly, only it's value is not a date but just "m/d/Y".
It would work if I'd set format='%m/%d/%Y', however, that defeats the purpose of the locale-aware SHORT_DATE_FORMAT. How can I properly solve that?
A possible solution is to overwrite the DateInput widget as follows.
from django.template.defaultfilters import date
class ShortFormatDateInput(DateInput):
def __init__(self, attrs=None):
super(DateInput, self).__init__(attrs)
def _format_value(self, value):
return date(value, formats.get_format("SHORT_DATE_FORMAT"))
It overwrites the super constructor so that the date format cannot be changed manually anymore. Instead I'd like to show the date as defined in SHORT_DATE_FORMAT. To do that, the _format_value method can be overwritten to reuse the date method defined django.templates.
I am trying to set a readonly attribute to this specific field in django. What I hope to accomplish is the field's data shows but it cant be changed. How do I go about this? Below is what I've tried and isn't working for me.
class editcartform(ModelForm):
class Meta:
model = signedup
exclude = ['sessionid', 'price', 'paid', 'orderid', 'dancer_1_level', 'dancer_2_level', 'dancer_2_sex', 'dancer_1_sex']
widgets = {
'comp_name':Textarea(attrs={'readonly'}),
}
'comp_name':Textarea(attrs={'readonly':'readonly'}),
or
'comp_name':Textarea(attrs={'disabled':'disabled'}),
It may change depends on what you want.
I have an optional datefield in my form, when I save it and it's empty I got the validation error about the invalid format.
In my model, I wrote blank=True and null=True.
Model :
created = models.DateTimeField(blank=True,null=True)
Form :
class XxxForm(forms.ModelForm):
created=forms.DateField(required=False)
class Meta:
model = Xxx
Error :
u"" value has an invalid format. It must be in YYYY-MM-DD HH:MM format
Update :
I found the solution which is :
created = request.POST['created']
if not created:
created = None
It works that way ! thanks everyone
You need to use a DateTimeField in the form, not a DateField.
[EDIT]
Also try to drop created=forms.DateField(required=False) from your form declaration. It is not needed there since you have it in the model already.