forms.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. from django import forms
  2. from django.db.models import Count
  3. from extras.forms import CustomFieldForm, CustomFieldBulkEditForm, CustomFieldFilterForm
  4. from utilities.forms import BootstrapMixin, BulkImportForm, CommentField, CSVDataField, SlugField
  5. from .models import Tenant, TenantGroup
  6. def bulkedit_tenantgroup_choices():
  7. """
  8. Include an option to remove the currently assigned TenantGroup from a Tenant.
  9. """
  10. choices = [
  11. (None, '---------'),
  12. (0, 'None'),
  13. ]
  14. choices += [(g.pk, g.name) for g in TenantGroup.objects.all()]
  15. return choices
  16. def bulkedit_tenant_choices():
  17. """
  18. Include an option to remove the currently assigned Tenant from an object.
  19. """
  20. choices = [
  21. (None, '---------'),
  22. (0, 'None'),
  23. ]
  24. choices += [(t.pk, t.name) for t in Tenant.objects.all()]
  25. return choices
  26. #
  27. # Tenant groups
  28. #
  29. class TenantGroupForm(forms.ModelForm, BootstrapMixin):
  30. slug = SlugField()
  31. class Meta:
  32. model = TenantGroup
  33. fields = ['name', 'slug']
  34. #
  35. # Tenants
  36. #
  37. class TenantForm(BootstrapMixin, CustomFieldForm):
  38. slug = SlugField()
  39. comments = CommentField()
  40. class Meta:
  41. model = Tenant
  42. fields = ['name', 'slug', 'group', 'description', 'comments']
  43. class TenantFromCSVForm(forms.ModelForm):
  44. group = forms.ModelChoiceField(TenantGroup.objects.all(), required=False, to_field_name='name',
  45. error_messages={'invalid_choice': 'Group not found.'})
  46. class Meta:
  47. model = Tenant
  48. fields = ['name', 'slug', 'group', 'description']
  49. class TenantImportForm(BulkImportForm, BootstrapMixin):
  50. csv = CSVDataField(csv_form=TenantFromCSVForm)
  51. class TenantBulkEditForm(BootstrapMixin, CustomFieldBulkEditForm):
  52. pk = forms.ModelMultipleChoiceField(queryset=Tenant.objects.all(), widget=forms.MultipleHiddenInput)
  53. group = forms.TypedChoiceField(choices=bulkedit_tenantgroup_choices, coerce=int, required=False, label='Group')
  54. def tenant_group_choices():
  55. group_choices = TenantGroup.objects.annotate(tenant_count=Count('tenants'))
  56. return [(g.slug, u'{} ({})'.format(g.name, g.tenant_count)) for g in group_choices]
  57. class TenantFilterForm(BootstrapMixin, CustomFieldFilterForm):
  58. model = Tenant
  59. group = forms.MultipleChoiceField(required=False, choices=tenant_group_choices,
  60. widget=forms.SelectMultiple(attrs={'size': 8}))