|
| 1 | +from django import forms |
| 2 | + |
| 3 | +from ...nhsuk_forms.choice_field import MultipleChoiceField |
| 4 | +from ..models.tobacco_smoking_history import TobaccoSmokingHistoryTypes, TobaccoSmokingHistory |
| 5 | + |
| 6 | + |
| 7 | + |
| 8 | +class TypesTobaccoSmokingForm(forms.Form): |
| 9 | + |
| 10 | + value = MultipleChoiceField( |
| 11 | + choices=TobaccoSmokingHistoryTypes.choices, |
| 12 | + widget=forms.CheckboxSelectMultiple, |
| 13 | + label="What do you or have you smoked?", |
| 14 | + label_classes="nhsuk-fieldset__legend--m", |
| 15 | + hint="Select all that apply", |
| 16 | + error_messages={ |
| 17 | + "required": "Select the type of tobacco you smoke or have smoked" |
| 18 | + }, |
| 19 | + ) |
| 20 | + |
| 21 | + def __init__(self, *args, response_set, **kwargs): |
| 22 | + super().__init__(*args, **kwargs) |
| 23 | + self.response_set = response_set |
| 24 | + self.existing_types = list( |
| 25 | + response_set.tobacco_smoking_history.values_list('type', flat=True) |
| 26 | + ) |
| 27 | + self.fields["value"].initial = self.existing_types |
| 28 | + |
| 29 | + value_field=self['value'] |
| 30 | + value_field.add_hint_for_choice( |
| 31 | + TobaccoSmokingHistoryTypes.CIGARILLOS, |
| 32 | + "Cafe Creme or Signature cigars, roughly the size of a cigarette" |
| 33 | + ) |
| 34 | + |
| 35 | + |
| 36 | + def save(self, commit=True): |
| 37 | + if not self.is_valid(): |
| 38 | + return None |
| 39 | + |
| 40 | + self._delete_types_not_selected() |
| 41 | + return self._create_types_selected() |
| 42 | + |
| 43 | + |
| 44 | + def _delete_types_not_selected(self): |
| 45 | + for kind in self.existing_types: |
| 46 | + if kind not in self.cleaned_data["value"]: |
| 47 | + TobaccoSmokingHistory.objects.filter(response_set=self.response_set, type=kind).delete() |
| 48 | + |
| 49 | + |
| 50 | + def _create_types_selected(self): |
| 51 | + instances = [ |
| 52 | + TobaccoSmokingHistory(response_set=self.response_set, type=kind) |
| 53 | + for kind in self.cleaned_data["value"] |
| 54 | + if kind not in self.existing_types |
| 55 | + ] |
| 56 | + |
| 57 | + TobaccoSmokingHistory.objects.bulk_create(instances) |
| 58 | + |
| 59 | + return instances |
0 commit comments