forms.py 2.3 KB

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