diff --git a/whoisdb/forms.py b/whoisdb/forms.py index 1af6b4e..8339587 100644 --- a/whoisdb/forms.py +++ b/whoisdb/forms.py @@ -55,18 +55,34 @@ class MntFormMixin(object): for key in self.protectedFields: self.fields[key].disabled = True - #self.fields["mnt_by"].widget.attrs["data-role"] = "tagsinput" instance = getattr(self, "instance", None) + if not hasattr(self, "_create"): + self._create = not (instance and instance.pk) + mntWhens = [When(auth=self._user, then=2)] - if instance and instance.pk: + if not self._create: mntWhens.append(When(handle__in=instance.mnt_by.all().values_list("handle"), then=1)) mntQs = Maintainer.objects.annotate(card=Case(*mntWhens, default=0, output_field=IntegerField())).order_by("-card") + # NOTE: We cannot use distinct on a field as some db backends don't support it + #self.fields["mnt_by"].queryset = mntQs.distinct("handle") self.fields["mnt_by"].queryset = mntQs if "mnt_lower" in self.fields: self.fields["mnt_lower"].queryset = mntQs + def clean(self): + cleaned_data = super(MntFormMixin, self).clean() + + if not self.errors and self._create: + mnts = self._user.maintainer_set.all() + + for mnt in cleaned_data['mnt_by']: + if mnt in mnts: + break + else: + raise forms.ValidationError("On object creation at least one maintainer needs to be under your control") + class MntForm(WhoisObjectFormMixin, forms.ModelForm): class Meta: model = Maintainer