def generate_name(cls, hr_name, max_length=25): ''' Generate a URL-friendly name based on a given human-readable name. Normalizes given name, then looks for conflicting domains, addressing conflicts by adding "-1", "-2", etc. May return None if it fails to generate a new, unique name. Throws exception if it can't figure out a name, which shouldn't happen unless max_length is absurdly short. ''' from corehq.apps.domain.utils import get_domain_url_slug from corehq.apps.domain.dbaccessors import domain_or_deleted_domain_exists name = get_domain_url_slug(hr_name, max_length=max_length) if not name: raise NameUnavailableException if domain_or_deleted_domain_exists(name): prefix = name while len(prefix): name = next_available_name( prefix, Domain.get_names_by_prefix(prefix + '-')) if domain_or_deleted_domain_exists(name): # should never happen raise NameUnavailableException if len(name) <= max_length: return name prefix = prefix[:-1] raise NameUnavailableException return name
def test_deleted_domain_exists(self): x = Domain(name='x') x.save() y = Domain(name='y') y.save() y.delete(leave_tombstone=True) self.addCleanup(x.delete) self.addCleanup(y.delete) self.assertTrue(domain_exists('x')) self.assertFalse(deleted_domain_exists('x')) self.assertTrue(domain_or_deleted_domain_exists('x')) self.assertFalse(domain_exists('y')) self.assertTrue(deleted_domain_exists('y')) self.assertTrue(domain_or_deleted_domain_exists('y')) self.assertTrue(len(list(iter_all_domains_and_deleted_domains_with_name('x'))), 1) self.assertTrue(len(list(iter_all_domains_and_deleted_domains_with_name('y'))), 1)
def save(self, **params): from corehq.apps.domain.dbaccessors import domain_or_deleted_domain_exists self.last_modified = datetime.utcnow() if not self._rev: if domain_or_deleted_domain_exists(self.name): raise NameUnavailableException(self.name) # mark any new domain as timezone migration complete set_tz_migration_complete(self.name) super(Domain, self).save(**params) from corehq.apps.domain.signals import commcare_domain_post_save results = commcare_domain_post_save.send_robust(sender='domain', domain=self) log_signal_errors(results, "Error occurred during domain post_save (%s)", {'domain': self.name})