2

I had an application that was working nicely using a User class that I had defined. After working on this for a few weeks, I realized I needed user authentication, and decided to use django's User class instead (I didn't really understand how this worked when I started, as I'm very new to Django). I got rid of my ForeignKey relation to my custom User class, and added a ForeignKey relation to django.contrib.auth.models.User, however now when I use the Admin page to add a new object, I get:

Exception Type: IntegrityError at /admin/po/purchaseorder/add/
Exception Value: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`po`.`po_purchaseorder`, CONSTRAINT `django_user_id_refs_id_fe5f38af` FOREIGN KEY (`django_user_id`) REFERENCES `auth_user` (`id`))')

I really don't understand this error. Here's the relevant class code:

from django.contrib.auth.models import User

class PurchaseOrder(models.Model):
    user=models.ForeignKey(User)
    request_number = models.AutoField(primary_key=True)
    #More fields 

Can anyone give me any explanation about this error, and why I'm getting it now that I'm using the built in User, as opposed to my own class?

Daniel Rosenthal
  • 1,386
  • 4
  • 15
  • 32
  • did you do a migration after you changed the `FK` type ? – karthikr Jun 24 '13 at 15:30
  • No I didn't. Just deleted the database and re-created it (I'm in a development stage, so there wasn't any real data to worry about.) – Daniel Rosenthal Jun 24 '13 at 15:31
  • Then drop the database schema and recreate it using `syncdb` . You might be better off learning about `django-south` the way it works, as it is widely used to handle database schema changes after syncdb – karthikr Jun 24 '13 at 15:32

1 Answers1

3

What might had happened is that you updated your models to include the Django's User definition but haven't updated the database yet.

IntegrityErrors mean that some constraint will be violated in the Database if you perform the query. I'm sure that updating the database schema a.k.a python manage.py syncdb will do the trick.

If you are able to drop the schema and created again then that might solve it. If not, just updated the modified tables your models represent.

Hope this helps!

Paulo Bu
  • 29,294
  • 6
  • 74
  • 73
  • Yeah... that did the trick. It's strange because I dropped the database and recreated it (and did syncdb) before testing the changes, but That was exactly the problem. Thanks! – Daniel Rosenthal Jun 24 '13 at 15:33
  • I'm glad it worked :) Consider using `django south` for migrations. It's a little hard to get it first time but once you get it is very convenient :) – Paulo Bu Jun 24 '13 at 15:35