Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I cannot solve Django models.DateField ValidationError

I am stuck with an Error with models.DateField()

First, I did this.

models.py

from datetime import date, datetime
from django.db import models

class User(models.Model):
    uid = models.AutoField(primary_key=True)
    birthdate = models.DateField()

Then, I got,

$ python manage.py makemigrations
You are trying to add a non-nullable field 'birthdate' to user_profile without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py

So, I did,

models.py

from datetime import date, datetime
from django.db import models

class User(models.Model):
    uid = models.AutoField(primary_key=True)
    birthdate = models.DateField(default=date.today)

Then,

$ python manage.py migrate
django.core.exceptions.ValidationError: ["'' は無効な日付形式です。YYYY-MM-DD形式にしなければなりません。"]

The error means, like "'' is invalid for formate of date. You should change to YYYY-MM-DD".

How should I change this code? Thank you.

/// additional /// If I can, I don't want to INSERT date INTO birthdate field. But it seems I have to. Can I let it blank?

birthdate = models.DateField(null=True, blank=False)

didn't work.

Python 3.5.1 Django 1.9.1

like image 233
yamachan Avatar asked Aug 12 '26 00:08

yamachan


2 Answers

Sounds like your migration files are messed up. When you do a migration, django would create a migration file that records what you did. So in short, you changed your model code many times, but you never changed your migration file, or you are creating duplicate migration files.

The following should be what you want,

birthdate = models.DateField(null=True, blank=True)

But as you noticed, cleaning up all migration files that related to this change and create a new one should solve the problem.

like image 159
Shang Wang Avatar answered Aug 13 '26 12:08

Shang Wang


What you have tried should work:

birthdate = models.DateField(null=True, blank=False)

This allows the database to accept null values (which it does during the migration) and blank means that django will not accept empty values from forms.

Make sure to delete migrations that have been made but not applied. Also try deleting all .pyc's in your project.

like image 20
knelson Avatar answered Aug 13 '26 13:08

knelson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!