Skip to content

Commit

Permalink
[#42] Handle Site creation in SitesConfigurationStep when no Sites mo…
Browse files Browse the repository at this point in the history
…dels
  • Loading branch information
swrichards committed Dec 19, 2024
1 parent 8f75d62 commit ff25fee
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
19 changes: 16 additions & 3 deletions django_setup_configuration/contrib/sites/steps.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.db import IntegrityError

from django_setup_configuration.configuration import BaseConfigurationStep
Expand All @@ -18,11 +19,23 @@ def execute(self, model: SitesConfigurationModel) -> None:
if not model.items:
raise ConfigurationRunFailed("Please specify one or more sites")

# We need to ensure the current site is updated, to make sure that `get_current`
# keeps working
first_site = model.items[0]

# We need to ensure the current site is updated, to make sure that `get_current`
# keeps working. The first site in the list is treated as the current site.
current_site = None

try:
current_site = Site.objects.get_current()
except (Site.DoesNotExist, ImproperlyConfigured):
current_site = Site()

# We have no current site, which means there is no site pointed to by
# settings.SITE_ID -- however, `get_current()` expects a Site with that ID
# to exist, so we have to make sure the created site receives that ID.
current_site.pk = getattr(settings, "SITE_ID")

try:
current_site.domain = first_site.domain
current_site.name = first_site.name
current_site.full_clean(exclude=("id",), validate_unique=False)
Expand Down
15 changes: 15 additions & 0 deletions tests/sites/test_sites_configuration_step.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,18 @@ def test_execute_configuration_step_failing_should_keep_existing_sites():

assert Site.objects.count() == 1
assert Site.objects.get() == site


@pytest.mark.django_db
def test_execute_configuration_step_creates_a_current_site_if_no_sites_exist():
Site.objects.all().delete()

execute_single_step(SitesConfigurationStep, yaml_source=CONFIG_FILE_PATH)

site1, site2 = Site.objects.all()

assert site1.domain == "domain.local1:8000"
assert site1.name == "Domain1"
assert site2.domain == "domain.local2:8000"
assert site2.name == "Domain2"
assert Site.objects.get_current() == site1

0 comments on commit ff25fee

Please sign in to comment.