carltongibson / django-filter

A generic system for filtering Django QuerySets based on user selections
https://django-filter.readthedocs.io/en/main/
Other
4.44k stars 767 forks source link

Deleting form fields and Initializing querysets order #1653

Open ilyadesign opened 5 months ago

ilyadesign commented 5 months ago
class StudentAchievementFilter(django_filters.FilterSet):
    def __init__(self, data=None, queryset=None, user=None, *args, **kwargs):
        super().__init__(data=data, queryset=queryset, *args, **kwargs)
        if user.get_group == 'teacher':
            del self.form.fields['teacher']
            self.filters['student'].queryset = user.teacher.get_students
            self.filters['team'].queryset = user.teacher.get_active_teams

The issue arises when del self.form.fields['teacher'] is placed before updating the querysets for 'student' and 'team'. In this scenario, it seems that the changes to the querysets do not get properly initialized.

Placing the deletion of the 'teacher' field before updating the querysets might interfere with the initialization process, possibly due to the internal mechanics of how Django handles form fields and queryset modifications. As a result, the querysets for 'student' and 'team' are not initialized.

carltongibson commented 5 months ago

Yes, don't access the form until after the filters are configured.