I have a filter where I need to access the request.user
. However, django-filter does not pass it. Without using the messy inspect.stack()
is there a way to get the current user in the method member_filter
below?
class ClubFilter(django_filters.FilterSet):
member = django_filters.MethodFilter(action='member_filter')
class Meta:
model = Club
fields = ['member']
def member_filter(self, queryset, value):
# get current user here so I can filter on it.
return queryset.filter(user=???)
For example this works but feels wrong...
def member_filter(self, queryset, value):
import inspect
request_user = None
for frame_record in inspect.stack():
if frame_record[3] == 'get_response':
request_user = frame_record[0].f_locals['request'].user
print(request_user)
is there maybe a way to add this to some middleware that injects user into all methods? Or is there a better way?
API Guide 1 DjangoFilterBackend. The django-filter library includes a DjangoFilterBackend class which supports highly customizable field filtering for REST framework. 2 SearchFilter. The SearchFilter class supports simple single query parameter based searching, and is based on the Django admin's search functionality. 3 OrderingFilter. ...
The djangorestframework-word-filter developed as alternative to filters.SearchFilter which will search full word in text, or exact match. django-url-filter provides a safe way to filter data via human-friendly URLs.
The SearchFilter class supports simple single query parameter based searching, and is based on the Django admin's search functionality. When in use, the browsable API will include a SearchFilter control: The SearchFilter class will only be applied if the view has a search_fields attribute set.
Upon Company creation, whether it’s a functional view or a CBV, you’ll have access to the request in the view processing the company’s creation. From there, you can assign the company’s user. If you’re using a CBV, you can override the form_valid function and assign the user from self.request.user. Here’s the Django documentation on CBVs.
Yes, you can do it, and it's very easy.
First, define __init__
method in your ClubFilter
class that will take one extra argument:
class ClubFilter(django_filters.FilterSet):
# ...
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(ClubFilter, self).__init__(*args, **kwargs)
With having your user saved into attribute inside ClubFilter
, you can use it in your filter. Just remember to pass current user from your view inside FilterSet
.
Try self.request.user
.
Why it must work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With