cook: improve create_site ordering of operations (#73207)

The logic is changed to match the one in ModelForm:
* first we try to get an object from the slug, or create a new one
* fields are filled
* we do a full_clean()
* then if needed the object is saved.

Keeping the full clean after the first .save() would raise an
IntegrityError because of the new unique constraints on the slug and
title fields.
This commit is contained in:
Benjamin Dauvergne 2023-03-14 20:44:47 +01:00
parent 645d6566f1
commit 00172e0673
1 changed files with 21 additions and 10 deletions

View File

@ -172,23 +172,34 @@ class Command(BaseCommand):
def create_site(self, klass, base_url, title, slug, template_name, variables):
if slug is None:
slug = klass.Extra.service_default_slug
obj, must_save = klass.objects.get_or_create(
slug=slug, defaults={'title': title, 'base_url': base_url, 'template_name': template_name}
)
try:
obj = klass.objects.get(slug=slug)
must_save = False
except klass.DoesNotExist:
obj = klass(slug=slug)
must_save = True
for attr in ('title', 'base_url', 'template_name'):
if getattr(obj, attr) != locals().get(attr):
setattr(obj, attr, locals().get(attr))
must_save = True
if must_save:
try:
obj.full_clean(
exclude=['last_operational_success_timestamp', 'last_operational_check_timestamp']
)
except ValidationError as e:
raise CommandError(str(e))
try:
obj.full_clean(
exclude=[
'secret_key',
'last_operational_success_timestamp',
'last_operational_check_timestamp',
]
)
except ValidationError as e:
raise CommandError(str(e))
if must_save:
obj.save()
self.must_notify = True
variables = variables or {}
obj_type = ContentType.objects.get_for_model(klass)
for variable_name in variables.keys():