diff --git a/registrasion/forms.py b/registrasion/forms.py index 229f7bc5..90bf1b48 100644 --- a/registrasion/forms.py +++ b/registrasion/forms.py @@ -1,3 +1,4 @@ +from registrasion.controllers.product import ProductController from registrasion.models import commerce from registrasion.models import inventory @@ -349,16 +350,31 @@ class VoucherForm(forms.Form): ) -class StaffProductsForm(forms.Form): - ''' Form for allowing staff to add an item to a user's cart. ''' +def staff_products_form_factory(user): + ''' Creates a StaffProductsForm that restricts the available products to + those that are available to a user. ''' - product = forms.ModelChoiceField( - widget=forms.Select, - queryset=inventory.Product.objects.all(), - ) + products = inventory.Product.objects.all() + products = ProductController.available_products(user, products=products) - quantity = forms.IntegerField( - min_value=0, - ) + product_ids = [product.id for product in products] + product_set = inventory.Product.objects.filter(id__in=product_ids) -StaffProductsFormSet = forms.formset_factory(StaffProductsForm) + class StaffProductsForm(forms.Form): + ''' Form for allowing staff to add an item to a user's cart. ''' + + product = forms.ModelChoiceField( + widget=forms.Select, + queryset=product_set, + ) + + quantity = forms.IntegerField( + min_value=0, + ) + + return StaffProductsForm + +def staff_products_formset_factory(user): + ''' Creates a formset of StaffProductsForm for the given user. ''' + form_type = staff_products_form_factory(user) + return forms.formset_factory(form_type) diff --git a/registrasion/views.py b/registrasion/views.py index f457a629..a7cf2391 100644 --- a/registrasion/views.py +++ b/registrasion/views.py @@ -819,7 +819,8 @@ def amend_registration(request, user_id): ).select_related("product") initial = [{"product": i.product, "quantity": i.quantity} for i in items] - formset = forms.StaffProductsFormSet( + StaffProductsFormSet = forms.staff_products_formset_factory(user) + formset = StaffProductsFormSet( request.POST or None, initial=initial, prefix="products",