Commit b78c5b73 authored by ljf's avatar ljf
Browse files

[enh] Autocreate config

parent 76972e66
...@@ -17,7 +17,7 @@ technical informations of a subscription. ...@@ -17,7 +17,7 @@ technical informations of a subscription.
To add a new configuration backend, you have to create a new app with a model To add a new configuration backend, you have to create a new app with a model
which inherit from Configuration. which inherit from Configuration.
Your model can implement Meta verbose_name to have human readable name and a Your model can implement Meta verbose_name to have human readable name and a
url_namespace variable to specify the url namespace used by this model. url_namespace variable to specify the url namespace used by this model.
""" """
...@@ -35,9 +35,9 @@ class Configuration(PolymorphicModel): ...@@ -35,9 +35,9 @@ class Configuration(PolymorphicModel):
Génère automatiquement la liste de choix possibles de configurations Génère automatiquement la liste de choix possibles de configurations
en fonction des classes enfants de Configuration en fonction des classes enfants de Configuration
""" """
return tuple((x().__class__.__name__,x()._meta.verbose_name) return tuple((x().__class__.__name__,x()._meta.verbose_name)
for x in Configuration.__subclasses__()) for x in Configuration.__subclasses__())
def model_name(self): def model_name(self):
return self.__class__.__name__ return self.__class__.__name__
model_name.short_description = 'Nom du modèle' model_name.short_description = 'Nom du modèle'
...@@ -52,7 +52,7 @@ class Configuration(PolymorphicModel): ...@@ -52,7 +52,7 @@ class Configuration(PolymorphicModel):
Une url doit être nommée "details" Une url doit être nommée "details"
""" """
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
return reverse('%s:details' % self.get_url_namespace(), return reverse('%s:details' % self.get_url_namespace(),
args=[str(self.id)]) args=[str(self.id)])
def get_url_namespace(self): def get_url_namespace(self):
...@@ -66,10 +66,33 @@ class Configuration(PolymorphicModel): ...@@ -66,10 +66,33 @@ class Configuration(PolymorphicModel):
else: else:
return self.model_name().lower() return self.model_name().lower()
def save(self, **kwargs):
self.clean()
os = self.offersubscription
for offer_ip_pool in os.offer.offerippool_set.order_by('-to_assign'):
IPSubnet.objects.create(
configuration=self,
ip_pool=offer_ip_pool.ip_pool)
return super(Configuration, self).save(**kwargs)
class Meta: class Meta:
verbose_name = 'configuration' verbose_name = 'configuration'
@receiver(post_save, sender=OfferSubscription)
def offer_subscription_event(sender, **kwargs):
os = kwargs['instance']
if not hasattr(os, 'configuration'):
config_cls = None
for subconfig_cls in Configuration.__subclasses__():
if subconfig_cls().__class__.__name__ == os.offer.configuration_type:
config_cls = subconfig_cls
break
if config_cls is not None:
config = config_cls.objects.create(offersubscription=os)
@receiver(post_save, sender=IPSubnet) @receiver(post_save, sender=IPSubnet)
@receiver(post_delete, sender=IPSubnet) @receiver(post_delete, sender=IPSubnet)
def subnet_event(sender, **kwargs): def subnet_event(sender, **kwargs):
......
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('offers', '0009_auto_20170818_1529'),
]
operations = [
migrations.AlterModelOptions(
name='offerippool',
options={'ordering': ['-to_assign'], 'verbose_name': "pool d'IP", 'verbose_name_plural': "pools d'IP"},
),
migrations.RenameField(
model_name='offer',
old_name='ippools',
new_name='ip_pools',
),
migrations.RenameField(
model_name='offerippool',
old_name='ippool',
new_name='ip_pool',
),
]
...@@ -46,7 +46,7 @@ class Offer(models.Model): ...@@ -46,7 +46,7 @@ class Offer(models.Model):
verbose_name='n\'est pas facturable', verbose_name='n\'est pas facturable',
help_text='L\'offre ne sera pas facturée par la commande charge_members') help_text='L\'offre ne sera pas facturée par la commande charge_members')
ippools = models.ManyToManyField(IPPool, through='OfferIPPool') ip_pools = models.ManyToManyField(IPPool, through='OfferIPPool')
def get_configuration_type_display(self): def get_configuration_type_display(self):
""" """
...@@ -86,7 +86,7 @@ class Offer(models.Model): ...@@ -86,7 +86,7 @@ class Offer(models.Model):
class OfferIPPool(models.Model): class OfferIPPool(models.Model):
offer = models.ForeignKey(Offer, offer = models.ForeignKey(Offer,
verbose_name='offre') verbose_name='offre')
ippool = models.ForeignKey(IPPool, ip_pool = models.ForeignKey(IPPool,
verbose_name='pool d\'IP') verbose_name='pool d\'IP')
to_assign = models.BooleanField(default=False, to_assign = models.BooleanField(default=False,
verbose_name='assignation par défaut') verbose_name='assignation par défaut')
......
...@@ -111,6 +111,10 @@ class IPSubnet(models.Model): ...@@ -111,6 +111,10 @@ class IPSubnet(models.Model):
self.validate_inclusion() self.validate_inclusion()
self.validate_reverse_dns() self.validate_reverse_dns()
def save(self, **kwargs):
self.clean()
return super(IPSubnet, self).save(**kwargs)
def __unicode__(self): def __unicode__(self):
return str(self.inet) return str(self.inet)
......
...@@ -14,7 +14,7 @@ from coin import validation ...@@ -14,7 +14,7 @@ from coin import validation
class HousingConfiguration(Configuration): class HousingConfiguration(Configuration):
url_namespace = "housing" url_namespace = "housing"
activated = models.BooleanField(default=False, verbose_name='activé') activated = models.BooleanField(default=True, verbose_name='activé')
ipv4_endpoint = InetAddressField(validators=[validation.validate_v4], ipv4_endpoint = InetAddressField(validators=[validation.validate_v4],
verbose_name="IPv4", blank=True, null=True, verbose_name="IPv4", blank=True, null=True,
help_text="Adresse IPv4 utilisée par " help_text="Adresse IPv4 utilisée par "
...@@ -93,7 +93,7 @@ class HousingConfiguration(Configuration): ...@@ -93,7 +93,7 @@ class HousingConfiguration(Configuration):
def clean(self): def clean(self):
# If saving for the first time and IP endpoints are not specified, # If saving for the first time and IP endpoints are not specified,
# generate them automatically. # generate them automatically.
if self.pk is None: if self.ipv4_endpoint is None or self.ipv6_endpoint is None:
self.generate_endpoints() self.generate_endpoints()
self.check_endpoints() self.check_endpoints()
......
...@@ -23,7 +23,7 @@ class VPNConfiguration(CoinLdapSyncMixin, Configuration): ...@@ -23,7 +23,7 @@ class VPNConfiguration(CoinLdapSyncMixin, Configuration):
# 'offers.OfferSubscription', # 'offers.OfferSubscription',
# related_name=backend_name, # related_name=backend_name,
# validators=[ValidateBackendType(backend_name)]) # validators=[ValidateBackendType(backend_name)])
activated = models.BooleanField(default=False, verbose_name='activé') activated = models.BooleanField(default=True, verbose_name='activé')
login = models.CharField(max_length=50, unique=True, blank=True, login = models.CharField(max_length=50, unique=True, blank=True,
verbose_name="identifiant", verbose_name="identifiant",
help_text="Laisser vide pour une génération automatique") help_text="Laisser vide pour une génération automatique")
...@@ -141,9 +141,9 @@ class VPNConfiguration(CoinLdapSyncMixin, Configuration): ...@@ -141,9 +141,9 @@ class VPNConfiguration(CoinLdapSyncMixin, Configuration):
ValidationError("Impossible de générer un login VPN") ValidationError("Impossible de générer un login VPN")
# Hash password if needed # Hash password if needed
self.password = utils.ldap_hash(self.password) self.password = utils.ldap_hash(self.password)
# If saving for the first time and IP endpoints are not specified, # If IP endpoints are not specified,
# generate them automatically. # generate them automatically.
if self.pk is None: if self.ipv4_endpoint is None or self.ipv6_endpoint is None:
self.generate_endpoints() self.generate_endpoints()
self.check_endpoints() self.check_endpoints()
......
...@@ -24,7 +24,7 @@ PROTOCOLE_TYPES = ( ...@@ -24,7 +24,7 @@ PROTOCOLE_TYPES = (
class VPSConfiguration(Configuration): class VPSConfiguration(Configuration):
url_namespace = "vps" url_namespace = "vps"
activated = models.BooleanField(default=False, verbose_name='activé') activated = models.BooleanField(default=True, verbose_name='activé')
ipv4_endpoint = InetAddressField(validators=[validation.validate_v4], ipv4_endpoint = InetAddressField(validators=[validation.validate_v4],
verbose_name="IPv4", blank=True, null=True, verbose_name="IPv4", blank=True, null=True,
help_text="Adresse IPv4 utilisée par " help_text="Adresse IPv4 utilisée par "
...@@ -100,9 +100,9 @@ class VPSConfiguration(Configuration): ...@@ -100,9 +100,9 @@ class VPSConfiguration(Configuration):
raise ValidationError(error.format(self.ipv6_endpoint)) raise ValidationError(error.format(self.ipv6_endpoint))
def clean(self): def clean(self):
# If saving for the first time and IP endpoints are not specified, # If IP endpoints are not specified,
# generate them automatically. # generate them automatically.
if self.pk is None: if self.ipv4_endpoint is None or self.ipv6_endpoint is None:
self.generate_endpoints() self.generate_endpoints()
self.check_endpoints() self.check_endpoints()
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment