I want to pass request.user to a queryset in ModelchoiceFilter, because choice entry should be limited according to login user group. I try it, but getting kwargs in filters.py did not work.
models.py
class Score(models.Model):
group = models.ForeignKey(Group, null=True, blank=True, on_delete=models.DO_NOTHING)
member = models.ForeignKey(Member, on_delete=models.CASCADE,)
date = models.DateField()
lane = models.PositiveSmallIntegerField(null=True)
score = models.PositiveSmallIntegerField(null=True)
filters.py
class ScoreFilter(django_filters.FilterSet):
class Meta:
model = Score
fields = {'member': ['exact'],
'date': ['gte','lte'],
}
def __init__(self, *args, **kwargs):
group = kwargs.pop('group', None)
super(ScoreFilter, self).__init__(*args, **kwargs)
self.filters['date__gte'].label="Start Date"
self.filters['date__lte'].label="End Date"
self.filters['member'].queryset = Member.objects.filter(group=group)
views.py
@login_required(login_url='/login/')
def MemberResult(request, *args, **kwargs):
for group in request.user.groups.filter(Q(name='mon') | Q(name='wed')):
group = group
s_filter = ScoreFilter(request.GET, group=group, queryset=Score.objects.filter(group=group).order_by('-date')
I tried many solutions related to similar questions from this site, but could not solve yet.
Try this
s_filter = ScoreFilter(request.GET, user=request.user, queryset=Score.objects.filter(group=group).order_by('-date')
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
for group in self.user.groups.filter(Q(name='mon') | Q(name='wed')):
group = group
super(ScoreFilter, self).__init__(*args, **kwargs)
self.filters['date__gte'].label="Start Date"
self.filters['date__lte'].label="End Date"
self.filters['member'].queryset = Member.objects.filter(group=group)