unable to validate datetime field - django

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.

Related

Setting the Format for the Django DatetimeInput Widget

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

DateField in DRF django

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']

Why Django DateField doesn't accept empty values?

I have a model with a DateField field with blank = True and null = True.
It seems that is not possibile save an object with an empty value for the Datefield.
class ProjectTask(models.Model):
actual_start_date = models.DateField(blank=True, null=True)
Then try with Python console:
p = ProjectTask.objects.all().last()
p.actual_start_date = ""
p.save()
The results is:
venv/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1273, in to_python
params={'value': value},
django.core.exceptions.ValidationError: ["'' value has an invalid date format. It must be in YYYY-MM-DD format."]
I'm using Python 3.4, Django 1.9 and PostgreSQL.
Any suggestions?
Dates are not strings. If you want to pass a string, it needs to be converted to a date. Normally, your form would validate whether or not you had a valid date, but you've bypassed this by setting an empty string directly on the model.
If you don't want to set a value at all, then pass None.

How to save an empty datefield in django

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.

Elasticsearch and auto_query

In the database objects are named news and news test
class ItemIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True)
name = indexes.CharField(model_attr='name')
name_alt = indexes.CharField(model_attr='name_alt')
def get_model(self):
return Serial
>>> from haystack.query import SearchQuerySet
>>> sqs = SearchQuerySet().all()
>>> sqs.count()
4
>>> SearchQuerySet().auto_query('new') # not working all query!
[]
If use haystack.backends.simple_backend.SimpleEngine its working.
Django==1.5.1
Elasticsearch==0.90
django-haystack==master (2.0)
Why????
It doesn't look like you're populating the all import document field.
Your SearchIndex class has these fields:
text = indexes.CharField(document=True)
name = indexes.CharField(model_attr='name')
name_alt = indexes.CharField(model_attr='name_alt')
You've defined the data source for name and name_alt but not for text. The output from your command line search shows that that field is empty in the search index. You have several options:
Populate that field from a model attribute
Use a prepare_FOO method to prepare the content for that field
Use a template, using the use_template argument for the text field and include any and all content in that template
Now the follow up question is why did auto_query fail but a basic curl query work? Because auto_query is searching the content - the document - and that's missing.