ContentType matching query does not exist on post_syncdb
Asked Answered
O

1

4

I am trying to add add some data to the database as soon as tables are created, using the post_syncdb signal.

signals.post_syncdb.connect(init)

Then in the init function, I want to set permission, so I use

ct = ContentType.objects.get(app_label='news', model='Article')
Permission(name='Approve articles', codename='can_approve_article', content_type=ct)

But if I drop all the tables and run syncdb, I get

...
File "...\base\functions\init.py", line 11, in init
  ct = ContentType.objects.get(app_label='news', model='Article')
...
django.contrib.contenttypes.models.DoesNotExist: ContentType matching query does not exist.

Some tests I have done:

  • It works fine if I try this code outside syncdb.
  • It also works fine if I let syncdb create all the tables without this code, and then add this code and run syncdb without it having to make any changes.
  • AND I am pretty sure it used to work, but I changed a lot of things in other places since then, so I don't know where to start.
  • I get the same error for other models in different apps.
  • The signal is fired about 10 times, only the first few times throw the error.

Thanks a lot for any hints!

Overcoat answered 26/7, 2012 at 15:40 Comment(1)
The "solution" now is to catch the DoesNotExist exception and pass. During one of the later times the signal is fired, the contenttype can be determined and things work. It works, but I am still curious for a more pretty solution if anyone has one.Overcoat
L
7

Add this to the beginning of your init function:

 from django.contrib.contenttypes.management import update_all_contenttypes
 update_all_contenttypes() # make sure all content types exist
Latria answered 12/7, 2013 at 12:15 Comment(1)
This no longer works in Django 1.10 - not sure when update_all_contenttypes was removed or what the replacement command is.Jala

© 2022 - 2024 — McMap. All rights reserved.