Skip to content

Commit

Permalink
Filter home choices by user status
Browse files Browse the repository at this point in the history
  • Loading branch information
brylie committed Jan 5, 2024
1 parent ae67028 commit ae7dc67
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
6 changes: 6 additions & 0 deletions activities/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ class ResidentActivityFormView(LoginRequiredMixin, FormView):
success_url = reverse_lazy("activity-list-view")

def get_form_kwargs(self):
"""Override the get_form_kwargs method to pass the user to the form.
This will allow the form to filter the residents by the user's
homes or the superuser to filter by all homes.
"""

kwargs = super().get_form_kwargs()

kwargs["user"] = self.request.user
Expand Down
21 changes: 17 additions & 4 deletions metrics/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,20 @@ def prepare_resident_choices(residencies: QuerySet[Residency]) -> list[tuple[int

def get_resident_choices(user=None):
# Fetch Residency objects with related 'home' and 'resident' in a single query
residencies = Residency.objects.filter(move_out__isnull=True).select_related(
if user.is_superuser:
residencies = Residency.objects.filter(move_out__isnull=True)
else:
residencies = Residency.objects.filter(
home__in=user.homes.all(),
move_out__isnull=True,
)

residencies.select_related(
"home",
"resident",
)

resident_choices = prepare_resident_choices(residencies)
resident_choices = prepare_resident_choices(residencies=residencies)

return resident_choices

Expand All @@ -92,9 +100,14 @@ class ResidentActivityForm(forms.Form):
activity_minutes = forms.IntegerField()
caregiver_role = forms.ChoiceField(choices=caregiver_role_choices)

def __init__(self, user: user_model, *args, **kwargs):
super().__init__(*args, **kwargs)
def __init__(self, *args, **kwargs):
"""Initialize the form.
Include the request user in the form kwargs if available so it
can be used to filter the resident choices.
"""
user = kwargs.pop("user", None)

super().__init__(*args, **kwargs)

self.fields["residents"].choices = get_resident_choices(user=user)

0 comments on commit ae7dc67

Please sign in to comment.