Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: int() argument must be a string or a number, not 'datetime.datetime'

I have made App12/models.py module as:

from django.db import models

class Question(models.Model):

    ques_text=models.CharField(max_length=300)
    pub_date=models.DateTimeField('Published date')

    def __str__(self):
        return self.ques_text

class Choice(models.Model):

    # question=models.ForeignKey(Question)
    choice_text=models.CharField(max_length=300)
    votes=models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

Then i run the cmds

 python manage.py makemigrations App12
 python manage.py migrate

and then enter 2 records in the Question model as:

Question.objects.create(ques_text="How are you?",pub_date='timezone.now()') 
                 # and (ques_text="What are you doing?",pub_date='timezone.now()')

Then i realise that Question and Choice models should be in foreign key relation and uncomment the above commented statement in the models code

When i run the "python manage.py makemigrations App12", it is running fine but after that, i am getting the

"TypeError: int() argument must be a string or a number, not 'datetime.datetime"

error when i am running "python manage.py migrate" command.

Can anybody help me.How can i add a foreignkey relation between the Choice model and Question model now.

like image 975
Jagat Avatar asked Sep 07 '15 13:09

Jagat


2 Answers

From your migration file it's normal that you get this error, you are trying to store a datetime on a Foreignkey which need to be an int.

This is happened when the migration asked you which value will be set for old Choice rows because the new ForeignKey is required.

To resolve it, you can change the migration file and change the datetime.date... to a valid id from the Question table like the code bellow. Or delete the migration file and re-run ./manage.py makemigrations, when you will be asked about the default value prompt a valid Question id, not a datetime.

from future import unicode_literals
from django.db import models, migrations
import datetime

class Migration(migrations.Migration):
    dependencies = [ ('App11', '0003_remove_choice_question'), ]
    operations = [
        migrations.AddField(
            model_name='choice',
            name='question',
            field=models.ForeignKey(default=1, to='App11.Question'), preserve_default=False, ),
    ]
like image 89
Mounir Avatar answered Nov 11 '22 12:11

Mounir


pub_date should not be a string. Create your object as follows:

from django.utils import timezone
Question.objects.create(ques_text="How are you?",pub_date=timezone.now()) 
like image 37
Régis B. Avatar answered Nov 11 '22 12:11

Régis B.