management.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. """
  2. Creates the default Site object.
  3. """
  4. from django.apps import apps
  5. from django.core.management.color import no_style
  6. from django.db import DEFAULT_DB_ALIAS, connections, router
  7. from django.db.models import signals
  8. def create_default_site(app_config, verbosity=2, interactive=True, db=DEFAULT_DB_ALIAS, **kwargs):
  9. try:
  10. Site = apps.get_model('sites', 'Site')
  11. except LookupError:
  12. return
  13. if not router.allow_migrate(db, Site):
  14. return
  15. if not Site.objects.exists():
  16. # The default settings set SITE_ID = 1, and some tests in Django's test
  17. # suite rely on this value. However, if database sequences are reused
  18. # (e.g. in the test suite after flush/syncdb), it isn't guaranteed that
  19. # the next id will be 1, so we coerce it. See #15573 and #16353. This
  20. # can also crop up outside of tests - see #15346.
  21. if verbosity >= 2:
  22. print("Creating example.com Site object")
  23. Site(pk=1, domain="example.com", name="example.com").save(using=db)
  24. # We set an explicit pk instead of relying on auto-incrementation,
  25. # so we need to reset the database sequence. See #17415.
  26. sequence_sql = connections[db].ops.sequence_reset_sql(no_style(), [Site])
  27. if sequence_sql:
  28. if verbosity >= 2:
  29. print("Resetting sequence")
  30. with connections[db].cursor() as cursor:
  31. for command in sequence_sql:
  32. cursor.execute(command)
  33. Site.objects.clear_cache()
  34. signals.post_migrate.connect(create_default_site, sender=apps.get_app_config('sites'))