Error when migrating new User model - django

Just created a User model in my models.py to save the users in the database. The model looks like this:
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(_('username'), max_length=30, unique=True,
validators=[
validators.RegexValidator(re.compile('^[\w.#+-]+$'), _('Enter a valid username.'), _('invalid'))
])
first_name = models.CharField(_('first name'), max_length=30, blank=True, null=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True, null=True)
email = models.EmailField(_('email address'), max_length=255)
is_staff = models.BooleanField(_('staff status'), default=False,)
is_active = models.BooleanField(_('active'), default=False,)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email',]
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_full_name(self):
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
return self.first_name
def email_user(self, subject, message, from_email=None):
send_mail(subject, message, from_email, [self.email])
I've also added in settings.py this piece of code:
AUTH_USER_MODEL = "myapp.User"
However, when I try to makemigrations for applying the changes, it appears this error:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\core\management\__init__.py", line 353, in execute_from_command_line
utility.execute()
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\core\management\__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\core\management\base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\core\management\base.py", line 399, in execute
output = self.handle(*args, **options)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\core\management\commands\makemigrations.py", line 105, in handle
loader.project_state(),
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\db\migrations\loader.py", line 338, in project_state
return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps))
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\db\migrations\graph.py", line 280, in make_state
project_state = self.nodes[node].mutate_state(project_state, preserve=False)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\db\migrations\migration.py", line 88, in mutate_state
operation.state_forwards(self.app_label, new_state)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\db\migrations\operations\models.py", line 158, in state_forwards
apps = state.apps
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\utils\functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\db\migrations\state.py", line 162, in apps
return StateApps(self.real_apps, self.models)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\db\migrations\state.py", line 235, in __init__
raise ValueError(self._pending_models_error(pending_models))
ValueError: Unhandled pending operations for models:
myapp.user (referred to by fields: admin.LogEntry.user)
So I'm looking for info for possible solutions or causes for this error but can't figure out why it happens. May it have to be a problem with some previous migration? (if so, I have no clue of which nor why). I'd add more information if needed, but I'd really appreciate any clue of the cause of this error.

The custom user docs specifically warn against switching User model after you have already created migrations; there's too much dependency for that to work properly. You may need to delete your existing db and migrations and start from scratch.

Related

how to get user's last login with OneToOneField and display it on admin panel?

Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/Users/rustem/studypageback/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/Users/rustem/studypageback/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "/Users/rustem/studypageback/venv/lib/python3.6/site-packages/django/core/management/base.py", line 436, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
<class 'portal_users.admin.ProfileAdmin'>: (admin.E108) The value of 'list_display[10]' refers to 'user__last_login', which is not a callable, an attribute of 'ProfileAdmin', or an attribute or method on 'portal_users.Profile'.
System check identified 1 issue (0 silenced).
There is my code
models.py:
class Profile(models.Model):
user = models.OneToOneField(
User,
null=True,
related_name='profile',
on_delete=CUSTOM_SET_NULL,
)
student_id = models.IntegerField(
blank=True,
null=True,
verbose_name='ID студента/преподавателя',
help_text='Из 1С',
)
first_name = models.CharField(
max_length=200,
verbose_name='Имя',
blank=True,
)
last_name = models.CharField(
max_length=200,
verbose_name='Фамилия',
blank=True,
)
admin.py:
#admin.register(models.Profile)
class ProfileAdmin(admin.ModelAdmin):
list_display = [
'user',
'first_name',
'last_name',
'user__last_login',
]
You would need to add a custom method that would display the last login on admin:
class ProfileAdmin(admin.ModelAdmin):
list_display = ['user','first_name', 'last_name', 'get_last_login']
def get_last_login(self,instance):
return instance.user.last_login
get_last_login.short_description = "Last login"
More on this: Documentation on list_display

Django Serializer is not JSON serializable

I'm trying to serialize an object details which contains ForeignKey and OneToOneField.
Here is my Model:
user = models.OneToOneField(
"User",
on_delete=models.CASCADE,
null=False,
blank=False,
verbose_name="User",
help_text="The user who subscribed.",
related_name="subscription_information",
unique=True,
)
subscription = models.ForeignKey(
Subscription,
on_delete=models.CASCADE,
null=False,
blank=False,
related_name="subscription_information",
verbose_name="Subscription",
help_text="This is the subscription.",
)
subscription_type = models.IntegerField(
choices=SUBSCRIPTION_TYPES_CHOICES,
default=SubscriptionTypes.monthly,
null=False,
blank=False,
verbose_name="Subscription Type",
help_text="",
)
next_payment_amount = models.FloatField(
default=0.0,
null=False,
blank=True,
verbose_name="Subscription Plan Next Payment Amount",
help_text=(""),
)
next_payment_date = models.DateTimeField(
null=True,
blank=True,
default=None,
verbose_name="Next Payment Date",
help_text=(""),
)
payment_made = models.BooleanField(
null=False,
blank=True,
default=False,
verbose_name="Is Payment Made",
help_text=(
""
),
)
subscription_date = models.DateTimeField(
null=True,
blank=True,
default=None,
verbose_name="Subscription Date",
help_text="",
)
As you see User field is OneToOneField and Subscription field is foreign key.
And here is my serializer:
class SubscriptionInformationDetailSerializer(serializers.ModelSerializer):
class Meta:
model = SubscriptionInformation
fields = (
"id",
"user",
"subscription",
"subscription_type",
"next_payment_amount",
"next_payment_date",
"payment_made",
"subscription_date",
)
I want to return serialized SubscriptionInformation with this code:
subscription_information = SubscriptionInformation.objects.get(user_id=user.id)
serializer = SubscriptionInformationDetailSerializer(subscription_information, read_only=True)
return serializer
But it throws this error:
Traceback (most recent call last):
File "E:\Programming\project\venv\lib\site-packages\django\core\handlers\exception.py", line 42, in inner
response = get_response(request)
File "E:\Programming\project\venv\lib\site-packages\django\core\handlers\base.py", line 217, in _get_response
response = self.process_exception_by_middleware(e, request)
File "E:\Programming\project\venv\lib\site-packages\django\core\handlers\base.py", line 215, in _get_response
response = response.render()
File "E:\Programming\project\venv\lib\site-packages\django\template\response.py", line 109, in render
self.content = self.rendered_content
File "E:\Programming\project\venv\lib\site-packages\rest_framework\response.py", line 72, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "E:\Programming\project\venv\lib\site-packages\rest_framework\renderers.py", line 105, in render
allow_nan=not self.strict, separators=separators
File "E:\Programming\project\venv\lib\site-packages\rest_framework\utils\json.py", line 28, in dumps
return json.dumps(*args, **kwargs)
File "C:\Python27\Lib\json\__init__.py", line 251, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "C:\Python27\Lib\json\encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Python27\Lib\json\encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "E:\Programming\project\venv\lib\site-packages\rest_framework\utils\encoders.py", line 68, in default
return super(JSONEncoder, self).default(obj)
File "C:\Python27\Lib\json\encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: DetailSerializer(<Thing: Thing object>, read_only=True):
id = IntegerField(label='ID', read_only=True)
user = PrimaryKeyRelatedField(help_text='The user who subscribed.', queryset=User.objects.all(), validators=[<UniqueValidator(queryset=SubscriptionInformation.objects.all())>])
subscription = PrimaryKeyRelatedField(help_text='This is the subscription.', queryset=Subscription.objects.all())
subscription_type = ChoiceField(choices=((0, 'Monthly'), (1, 'Annual')), help_text='', label='Subscription Type', required=False, validators=[<django.core.validators.MinValueValidator object>, <django.core.validators.MaxValueValidator object>])
next_payment_amount = FloatField(help_text='', label='Subscription Plan Next Payment Amount', required=False)
next_payment_date = DateTimeField(allow_null=True, help_text='', label='Next Payment Date', required=False)
payment_made = BooleanField(help_text='', label='Is Payment Made', required=False)
subscription_date = DateTimeField(allow_null=True, help_text='', label='Subscription Date', required=False) is not JSON serializable
I couldn't understand why can't I serialize this. Why it's not JSON serializable
Ok, No problem with model and serializer. I just need to return the serializer.data. So my code should be like that:
subscription_information = SubscriptionInformation.objects.get(user_id=user.id)
serializer = SubscriptionInformationDetailSerializer(subscription_information, read_only=True)
return serializer.data

The value of 'list_display[5]' must not be a ManyToManyField

I am trying to create manytomany fields in one of the class, I am getting an error "The value of 'list_display[5]' must not be a ManyToManyField"
Need Help, Thanks in advance :)
class ShiftConfig(models.Model):
description = models.CharField(max_length=30)
start_time = models.TimeField()
end_time = models.TimeField()
def __str__(self):
return str(self.id) + ' : ' + str(self.start_time)
class FaultConfig(models.Model):
description = models.CharField(max_length=30)
message = models.ForeignKey(Message, null=True, on_delete=models.SET_NULL)
recipients = models.ForeignKey(UserGroup, null=True, on_delete=models.SET_NULL)
alert_time = models.DurationField(default=timedelta(0.0001))
repeat = models.PositiveSmallIntegerField()
escalated_fault = models.ForeignKey('self', null=True, on_delete=models.SET_NULL, blank=True)
def __str__(self):
return str(self.id) + ' : ' + str(self.description)
Here is the concerned class.
class WorkStation(models.Model):
name = models.CharField(max_length=30)
location = models.CharField(max_length=30)
department= models.ForeignKey(Department, null=True, on_delete=models.SET_NULL)
current_user=models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
allowed_fault_configs = models.ManyToManyField(FaultConfig, through='WFMembership', through_fields=('workstation', 'fault_config'))
allowed_shift_configs = models.ManyToManyField(ShiftConfig, through='WSMembership', through_fields=('workstation', 'shift_config'))
def __str__(self):
return str(self.id) + ' : ' + str(self.name)
class WFMembership(models.Model):
workstation = models.ForeignKey(WorkStation, on_delete=models.CASCADE)
fault_config = models.ForeignKey(FaultConfig, on_delete=models.CASCADE)
class WSMembership(models.Model):
workstation = models.ForeignKey(WorkStation, on_delete=models.CASCADE)
shift_config = models.ForeignKey(ShiftConfig, on_delete=models.CASCADE)
Here is the error which mentions that the field must not be ManyToManyField
Watching for file changes with StatReloader
Performing system checks...
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Program Files\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Program Files\Python36\lib\site-packages\channels\management\commands\runserver.py", line 69, in inner_run
self.check(display_num_errors=True)
File "C:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 441, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
<class 'andon.admin.WorkStation'>: (admin.E109) The value of 'list_display[5]' must not be a ManyToManyField.
<class 'andon.admin.WorkStation'>: (admin.E109) The value of 'list_display[6]' must not be a ManyToManyField.
System check identified 2 issues (0 silenced).
Here is the admin.py for Workstation
#admin.register(WorkStation)
class WorkStation(admin.ModelAdmin):
list_display = ('id', 'name','location','department','current_user','allowed_fault_configs', 'allowed_shift_configs')
list_display_links = ('id', 'name')
Can you post your admin.py? Specifically andon.admin.WorkStation?
Please refer to Django documentation for ManytoManyField usage in admin console.
You can write a custom function to retrieve those values from the ManyToManyField.

How to print foreign key of this model in django?

Model File
class Report_item(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
title = models.CharField(max_length=255, help_text='*Title for the post e.g. item identity')
item_type = models.CharField(default="", max_length=100,
help_text='*Enter the item name you found e.g. Marksheet,key,wallet')
location = models.CharField(max_length=60, help_text='*Enter the address/street where you find this item')
city = models.CharField(max_length=60, help_text='*Enter the city name')
date = models.DateTimeField(default=timezone.now)
Description = models.TextField(help_text='*Enter full description about item')
publish = models.BooleanField(default=False)
image = models.FileField(default="add Item image",
help_text='*Please uplocad a item image to identify by the owner')
def __str__(self):
return self.title + " " + str(self.publish)
def get_absolute_url(self):
return reverse('feed:detail', kwargs={'pk': self.pk})
class Meta:
ordering = ["-date"]
I print my title in the shell.
>>> qs=Report_item.objects.filter(id=3)
>>> print(qs[0].title)
bunch of key with home keyring
But I got an error when I tried to print(qs[0].owner)
My foreign key is the Django auth user.
>>> print(qs[0].owner)
Traceback (most recent call last):
File "/home/imsaiful/Desktop/local_repo/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 178, in __get__
rel_obj = getattr(instance, self.cache_name)
AttributeError: 'Report_item' object has no attribute '_owner_cache'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/imsaiful/Desktop/local_repo/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 184, in __get__
rel_obj = self.get_object(instance)
File "/home/imsaiful/Desktop/local_repo/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 159, in get_object
return qs.get(self.field.get_reverse_related_filter(instance))
File "/home/imsaiful/Desktop/local_repo/myvenv/lib/python3.6/site-packages/django/db/models/query.py", line 379, in get
self.model._meta.object_name
django.contrib.auth.models.DoesNotExist: User matching query does not exist.
admin section image:
https://drive.google.com/file/d/1lQ-TcdaTCxj-cmnzfhlGZXql-KbWpIjW/view?usp=sharing

south error with django

my old models.py :
from django.db import models
from taggit.managers import TaggableManager
from django.utils.encoding import smart_unicode
import markdown
class PublishedManager(models.Manager):
def get_query_set(self):
return super(PublishedManager, self).get_query_set().filter\
(is_published=True)
class Category(models.Model):
name = models.CharField(max_length=55)
def __unicode__(self):
return u"%s" %(self.name)
class BookMarks(models.Model):
name = models.CharField(max_length=255)
url = models.URLField()
date_time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return u"%s %s %s" %(self.name, self.url, self.date_time)
class Post(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True)
excerpt = models.TextField(blank=True, help_text="A small teaser of\
your content")
content = models.TextField(blank=True, null=True)
contentmarkdown = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
is_published = models.BooleanField(default=True)
objects = models.Manager()
published_objects = PublishedManager()
tags = TaggableManager()
category = models.ForeignKey(Category)
def save(self):
self.content = markdown.markdown(self.contentmarkdown)
super(Post, self).save() # Call the "real" save() method.
class Meta:
ordering = ("date_created",)
def __unicode__(self):
return smart_unicode("%s %s %s %s %s" %(self.title, self.content, self.is_published, self.category, self.tags))
def get_absolute_url(self):
return "/posts/%s/" % self.id
class Book(models.Model):
name = models.CharField(max_length=55)
author = models.CharField(max_length=55)
image = models.ImageField(upload_to="static/img/books/")
body = models.TextField(blank=True, null=True)
bodymarkdown = models.TextField()
def __unicode__(self):
return u"%s %s" %(self.name, self.author)
def get_absolute_url(self):
return "/books/%s/" % self
.id
and after add "category = models.ForeignKey(Category)" this field to Book and BookMarks table, my new models.py like this:
from django.db import models
from taggit.managers import TaggableManager
from django.utils.encoding import smart_unicode
import markdown
class PublishedManager(models.Manager):
def get_query_set(self):
return super(PublishedManager, self).get_query_set().filter\
(is_published=True)
class Category(models.Model):
name = models.CharField(max_length=55)
def __unicode__(self):
return u"%s" %(self.name)
class BookMarks(models.Model):
name = models.CharField(max_length=255)
url = models.URLField()
date_time = models.DateTimeField(auto_now_add=True)
category = models.ForeignKey(Category)
def __unicode__(self):
return u"%s %s %s" %(self.name, self.url, self.date_time)
class Post(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True)
excerpt = models.TextField(blank=True, help_text="A small teaser of\
your content")
content = models.TextField(blank=True, null=True)
contentmarkdown = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
is_published = models.BooleanField(default=True)
objects = models.Manager()
published_objects = PublishedManager()
tags = TaggableManager()
category = models.ForeignKey(Category)
def save(self):
self.content = markdown.markdown(self.contentmarkdown)
super(Post, self).save() # Call the "real" save() method.
class Meta:
ordering = ("date_created",)
def __unicode__(self):
return smart_unicode("%s %s %s %s %s" %(self.title, self.content, self.is_published, self.category, self.tags))
def get_absolute_url(self):
return "/posts/%s/" % self.id
class Book(models.Model):
name = models.CharField(max_length=55)
author = models.CharField(max_length=55)
image = models.ImageField(upload_to="static/img/books/")
body = models.TextField(blank=True, null=True)
bodymarkdown = models.TextField()
category = models.ForeignKey(Category)
def __unicode__(self):
return u"%s %s" %(self.name, self.author)
def get_absolute_url(self):
return "/books/%s/" % self.id
class Errors(models.Model):
name = models.CharField(max_length=255)
created = models.DateTimeField(auto_now_add=True)
body = models.TextField(blank=True, null=True)
bodymarkdown = models.TextField()
def __unicode__(self):
return self.name
def get_absolute_url(self):
return "/errors/%s/" % self.id
I used south. Everything was going OK but after this line:
? 1. Quit now, and add a default to the field in models.py
? 2. Specify a one-off value to use for existing columns now
? 3. Disable the backwards migration by raising an exception.
? Please select a choice: 2
? Please enter Python code for your one-off default value.
? The datetime module is available, so you can do e.g. datetime.date.today()
>>> datetime.datetime.now()
I get an error like this:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 232, in execute
output = self.handle(*args, **options)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/management/commands/migrate.py", line 108, in handle
ignore_ghosts = ignore_ghosts,
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/__init__.py", line 213, in migrate_app
success = migrator.migrate_many(target, workplan, database)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 235, in migrate_many
result = migrator.__class__.migrate_many(migrator, target, migrations, database)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 310, in migrate_many
result = self.migrate(migration, database)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 133, in migrate
result = self.run(migration)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 106, in run
dry_run.run_migration(migration)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 191, in run_migration
self._run_migration(migration)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 178, in _run_migration
raise exceptions.FailedDryRun(migration, sys.exc_info())
south.exceptions.FailedDryRun: ! Error found during dry run of '0012_auto__del_field_book_category__add_field_book_category1__del_field_boo'! Aborting.
Traceback (most recent call last):
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 175, in _run_migration
migration_function()
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 57, in <lambda>
return (lambda: direction(orm))
File "/home/ada/mainproject/blog/migrations/0012_auto__del_field_book_category__add_field_book_category1__del_field_boo.py", line 17, in forwards
keep_default=False)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/db/generic.py", line 44, in _cache_clear
return func(self, table, *args, **opts)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/db/generic.py", line 402, in add_column
sql = self.column_sql(table_name, name, field)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/db/generic.py", line 688, in column_sql
default = field.get_db_prep_save(default, connection=self._get_connection())
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 991, in get_db_prep_save
connection=connection)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 292, in get_db_prep_save
prepared=False)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 284, in get_db_prep_value
value = self.get_prep_value(value)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 537, in get_prep_value
return int(value)
TypeError: int() argument must be a string or a number, not 'datetime.datetime'
Please can you tell me Why I get this error? What must I do?
Because your new category field is mandatory (you can't create a book or bookmark without giving it a category), south asked you what to do with the existing books and bookmarks in your database - your latest changes would have made all your current books / bookmarks invalid (since they don't have a category).
Your new category field is represented in your book/bookmark tables using a primary key of the category table. This primary key will likely be an integer (or possibly a string).
South asked you to supply a default primary key. Instead of supplying the primary key of an category object in your database (which would be an integer or a string). You've supplied a datatime object.
It's crapping out when it actually runs the migration because the field doesn't hold datetime objects. It holds integers (or strings). you need to create the migration again and add a valid primary key.