Q:

How do I pass only current user data to be filtered in django-filter?

I am using django-filter to filter my data. The issue is both the available options of the filters and the results are based on all the data, not only on the curent user.
models.py
class Product(models.Model):
    title = models.CharField(max_length=264)
    description = models.CharField(max_length=264)
    date_added = models.DateField(auto_now_add=True)
    time_added = models.TimeField(auto_now_add=True)
    user = models.ForeignKey(User, default=1, on_delete=models.CASCADE)

I used the code below to filter the results only on the current user:
filters.py
class ProductFilter(django_filters.FilterSet):

    class Meta:
        model = Product

    @property
    def qs(self):
        parent = super(ProductFilter, self).qs
        user = getattr(self.request, "user", None)
        return parent.filter(user=user).order_by("-timestamp")

In my views.py I tried to pass the queryset, but nothing changed:
class ProductsFilterView(LoginRequiredMixin, FilterView):
    model = Product
    filterset_class = ProductFilter

    def get_queryset(self, **kwargs):
        return self.model.objects.filter(user=self.request.user)

I am not sure how to limit the available filter options only on the current user's data.
So, summarizing how can I pass into the filterset just the current user's data and not pass the whole data into the filterset and then filter them on current user's data.

A:

filters.py
class ProductFilter(django_filters.FilterSet):

    class Meta:
        title = django_filters.CharFilter(lookup_expr='icontains')
        # And you can also do "lookup_expr='year__gt' and also 'year__lt'" 
        date_added = django_filters.NumberFilter(name='date_added', lookup_expr='year')
        class Meta:
            model = Product
            fields = [] #You can add fields that wants to be displayed

views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from .filters import ProductFilter

# Function Base View
@login_required
def productfilter(request):
     user = request.user
     product_list = Product.objects.filter(user=user)
     product_filter = ProductFilter(request.GET, queryset=product_list)
     return render(request, "template_name.html", {'products': product_list})

#Class Based View
class ProductsFilterView(LoginRequiredMixin, FilterView):
    context_object_name = 'products'
    template_name = 'template_name.html'
    filter_set = ProductFilter
    def get_queryset(self):
        return Product.objects.filter(user=self.request.user)

I hope this was helpful.

