Libin Thomas
Libin Thomas

Reputation: 969

Django - How to set date format for models.DateField()? Terminal keeps throwing date validation error

I could not find a way to change the format for models.Datefield(). My application accepts date input from users in the format "%m%d%YY". Is there any way I can change the date format for Datefield() django model? Please help

My models.py

from phonenumber_field.modelfields import PhoneNumberField

# Create your models here.
class reservations_db(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()
    phone = PhoneNumberField(blank=False)
    date = models.DateField(null=True, blank=False)
    time = models.TimeField()
    person = models.IntegerField()

    class Meta():
        verbose_name_plural = "Reservations list"

My views.py

from django.shortcuts import render
from .models import reservations_db

# Create your views here.
def reservation(request):
    if request.method == 'POST':
        object=reservations_db()
        object.name = request.POST['name']
        object.email = request.POST['email']
        object.phone = request.POST['phone']
        object.date = request.POST['date']
        object.time = request.POST['time']
        object.person = request.POST['person']
        object.save()


    return render(request,'reservation.html')

Migration file

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='reservations_db',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=100)),
                ('email', models.EmailField(max_length=254)),
                ('phone', phonenumber_field.modelfields.PhoneNumberField(max_length=128, region=None)),
                ('date', models.DateTimeField(null=True)),
                ('time', models.TimeField()),
                ('person', models.IntegerField()),
            ],
            options={
                'verbose_name_plural': 'Reservations list',
            },
        ),
    ]

Terminal error message:

  File "C:\Users\libin.thomas\Envs\freelancing\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\libin.thomas\Envs\freelancing\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\OneDrive - CACTUS\My Documents\GitHub\Libbys_restaurant\booktable\views.py", line 14, in reservation
    object.save()
  File "C:\Users\libin.thomas\Envs\freelancing\lib\site-packages\django\db\models\base.py", line 745, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Users\libin.thomas\Envs\freelancing\lib\site-packages\django\db\models\base.py", line 782, in save_base
    updated = self._save_table(
  File "C:\Users\libin.thomas\Envs\freelancing\lib\site-packages\django\db\models\base.py", line 887, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "C:\Users\libin.thomas\Envs\freelancing\lib\site-packages\django\db\models\base.py", line 924, in _do_insert
    return manager._insert(
  File "C:\Users\libin.thomas\Envs\freelancing\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\libin.thomas\Envs\freelancing\lib\site-packages\django\db\models\query.py", line 1204, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\Users\libin.thomas\Envs\freelancing\lib\site-packages\django\db\models\sql\compiler.py", line 1391, in execute_sql
    for sql, params in self.as_sql():
  File "C:\Users\libin.thomas\Envs\freelancing\lib\site-packages\django\db\models\sql\compiler.py", line 1334, in as_sql
    value_rows = [
  File "C:\Users\libin.thomas\Envs\freelancing\lib\site-packages\django\db\models\sql\compiler.py", line 1335, in <listcomp>
    [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  File "C:\Users\libin.thomas\Envs\freelancing\lib\site-packages\django\db\models\sql\compiler.py", line 1335, in <listcomp>
    [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  File "C:\Users\libin.thomas\Envs\freelancing\lib\site-packages\django\db\models\sql\compiler.py", line 1276, in prepare_value
    value = field.get_db_prep_save(value, connection=self.connection)
  File "C:\Users\libin.thomas\Envs\freelancing\lib\site-packages\django\db\models\fields\__init__.py", line 821, in get_db_prep_save
    return self.get_db_prep_value(value, connection=connection, prepared=False)
  File "C:\Users\libin.thomas\Envs\freelancing\lib\site-packages\django\db\models\fields\__init__.py", line 1220, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Users\libin.thomas\Envs\freelancing\lib\site-packages\django\db\models\fields\__init__.py", line 1215, in get_prep_value
    return self.to_python(value)
  File "C:\Users\libin.thomas\Envs\freelancing\lib\site-packages\django\db\models\fields\__init__.py", line 1187, in to_python
    raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['“8/25/2020” value has an invalid date format. It must be in YYYY-MM-DD format.']

Please note that I do not want to use froms.Datefield() option. Would appreciate if suggestions related to Forms field is avoided. Thanks in advance guys :)

Upvotes: 0

Views: 658

Answers (1)

MeL
MeL

Reputation: 1269

In your model you have a DateField, but in your migrations file it says DateTimeField, and this might be what is causing the issue. Change your migration file to what it should be, run your migrations again, and then it should work.

Using ModelForm instead - create a new forms.py file and put the following in there:

from django.forms import ModelForm
from app.models import reservations_db

class ReservationForm(ModelForm):
    class Meta:
        model = reservations_db  #Note that good practice is to capitalise your model names and they shouldn't be plural; a better name would therefore be Reservation
        fields = ('name', 'email', 'phone', 'date') #here you add all the fields you want in the form

Note from the documentation:

The generated Form class will have a form field for every model field specified, in the order specified in the fields attribute.

For more information: https://docs.djangoproject.com/en/3.1/topics/forms/modelforms/

Now you need to create the view, which can be something like this:

class AddReservation(CreateView):
    form_class = forms.ReservationForm
    success_url = reverse_lazy("")  #add relevant path
    template_name = "app/reservations.html" #add relevant template name

Django will handle all the validation. All you have to do is create a template, e.g. registration_form and use {{form.as_p}}.

Upvotes: 1

Related Questions