Parcourir la source

Refactor subscription filtering

Baptiste Jonglez il y a 11 ans
Parent
commit
04384ae535
2 fichiers modifiés avec 17 ajouts et 5 suppressions
  1. 14 0
      coin/offers/backends.py
  2. 3 5
      coin/vpn/forms.py

+ 14 - 0
coin/offers/backends.py

@@ -1,6 +1,10 @@
 # -*- coding: utf-8 -*-
 
+"""Various helpers designed to help configuration backends regarding
+repetitive tasks."""
+
 from django.core.exceptions import ValidationError
+from django.db.models import Q
 
 
 def ValidateBackendType(object):
@@ -17,9 +21,19 @@ def ValidateBackendType(object):
     forms.  But it does not protect us if we fiddle manually with the
     database: better safe than sorry.
     """
+
     def __init__(self, backend_name):
         self.backend = backend_name
 
     def __call__(self, subscription):
         if OfferSubscription.objects.get(pk=subscription).offer.backend != self.backend:
             raise ValidationError('Administrative subscription must have a "{}" backend.'.format(self.backend))
+
+
+def filter_subscriptions(backend_name, instance):
+    """Helper function for configuration backends, allowing to filter
+    subscriptions that have the right """
+    return Q(offer__backend=backend_name) & (
+        # Select "unassociated" subscriptions, plus our own
+        # subscription (in case we are editing the object).
+        Q((backend_name, None)) | Q((backend_name, instance.pk)))

+ 3 - 5
coin/vpn/forms.py

@@ -1,9 +1,9 @@
 # -*- coding: utf-8 -*-
 
 from django.forms import ModelForm
-from django.db.models import Q
 
 from coin.offers.models import OfferSubscription
+from coin.offers.backends import filter_subscriptions
 from coin.vpn.models import VPNSubscription
 
 
@@ -15,9 +15,7 @@ class VPNSubscriptionForm(ModelForm):
     def __init__(self, *args, **kwargs):
         super(VPNSubscriptionForm, self).__init__(*args, **kwargs)
         if self.instance:
-            query = Q(offer__backend="openvpn_ldap") & (
-                # Select "unassociated" subscriptions, plus our own
-                # subscription (in case we are editing the object).
-                Q(("openvpn_ldap", None)) | Q(("openvpn_ldap", self.instance.pk)))
+            query = filter_subscriptions(self.instance.backend_name,
+                                         self.instance)
             queryset = OfferSubscription.objects.filter(query)
             self.fields['administrative_subscription'].queryset = queryset