I want to add a column to a model in django. The database I am using is mysql. The earlier database file was;
class Student(models.Model):
name = models.CharField(max_length=20, validators=[validate_name])
password = models.CharField(max_length=100)
email = models.EmailField(max_length=50)
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__'
Now, I added following line too, after password:
repeat_password = models.CharField(max_length=100)
Now I am running following commands:
python manage.py makemigrations
python manage.py migrate
The first line results in 0001_initial.py
whose contents are:
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Student',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=20, validators=[ajax.models.validate_name])),
('password', models.CharField(max_length=100)),
('repeat_password', models.CharField(max_length=100)),
('email', models.EmailField(max_length=50)),
],
),
]
But, the second line doesn't add anything to the database:
mysql> desc ajax_student;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| password | varchar(100) | NO | | NULL | |
| email | varchar(10) | NO | | NULL | |
+----------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
I don't know what am I doing wrong? I looked for answer on SO, but none of them worked: Altering database tables in Django
Adding fields to an already existing database
Please help me to solve this.
Edit
Thank you for help every one. When I was adding the field repeat_password
, it was asking for a default value:
You are trying to add a non-nullable field 'repeat_password' to student 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
Select an option: 1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now()
So, what I did wrong was chose 1 option and deleted previous migrations. And, then run makemigrations
and migrations
, just to avoid rewriting default values. That's why I got the error.
But, when I choose second option and then giving a default value, I run above commands, it worked. The thing is I just wanted to save myself from providing a default value. I don't know why while adding extra field it is required, but while creating a field, it's not required.