Search code examples
djangodjango-formsdjango-filterdjango-filters

Django: filter database for current user


On my webpage I would like the user to filter the database by month and year.

To do so, I created a filters.py .

My problem: I did not manage the user to only filter its own data, but he is also able to see the data from the other users.

So far I have tried to use @login_required and the objects.filter(user=self.request.user) method. Both didn't solve my problem.

I would be grateful for any tipps!

Here my code:

models.py:

from django.db import models
from django.contrib.auth.models import User

class UserDetails(models.Model):
   user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="new_spending", null=True) 
   expense_name = models.CharField(max_length=255)
   cost = models.FloatField()
   date_added = models.DateTimeField()

filters.py

from .models import UserDetails
import django_filters

class BudgetFilter(django_filters.FilterSet):
    year_added = django_filters.NumberFilter(field_name='date_added', lookup_expr='year', label='Year   [yyyy]')# lookup_expr='year',
    month_added = django_filters.NumberFilter(field_name='date_added', lookup_expr='month', label='Month [mm]')
    class Meta:
        model = UserDetails
        fields = ['year_added', 'month_added']

views.py

from django.shortcuts import render
from .models import UserDetails
from .filters import BudgetFilter
from django.contrib.auth.decorators import login_required

@login_required
def search(request):

    lista = UserDetails.objects.filter(user= request.user)
    filtered_list = BudgetFilter(request.GET, queryset=lista)
    return render(request, 'budget_app/user_list.html', {
        'filter': filtered_list,
        'users': lista
        })

urls.py:

from django.urls import path
from . import views 
from django_filters.views import FilterView
from .filters import BudgetFilter

urlpatterns = [
     ...
     path('search/', FilterView.as_view(filterset_class=BudgetFilter,
        template_name='budget_app/user_list.html'), name='search'),
     ]

html file:

{% extends 'budget_app/budget_base.html' %}



{% block content %}
  <form method="get">
    {{ filter.form.as_p }}
    <button type="submit">Search</button>
  </form>
  <ul>
  {% for item in filter.qs %}

    <li>{{ item.title }} - {{ item.date_added }}</li>
  {% endfor %}
  </ul>
{% endblock %}

Thank you!


Solution

  • You here trigger a FilterView, not the search function, hence regardless what you change, it will not change anything. That being said, I think it might be better here to subclass the FilterView:

    # app/views.py
    
    from django.contrib.auth.mixins import LoginRequiredMixin
    from django_filters.views import FilterView
    from .models import UserDetails
    
    class UserDetailsFilterView(FilterView):
        filterset_class=BudgetFilter
        template_name='budget_app/user_list.html'
    
        def get_queryset(self):
            return UserDetails.objects.filter(user=self.request.user)

    Then in the urls.py you can just use the UserDetailsFilterView:

    # app/urls.py
    
    from django.urls import path
    from . import views
    
    urlpatterns = [
         ...
         path('search/', views.UserDetailsFilterView.as_view(), name='search'),
    ]