my goal is to have a 'user_profile' page that displays relevant information of the user of interest.
Furthermore, the 'user_profile' page should include all the posts that were created by the respective user as new blog entries.
These posts, however, should be filterable with the application 'django-filter' and be paginated. At the moment I have difficulties to paginate the filtered posts. So my question is how to achieve the latter?
So far, I used following approach:
filters.py
import django_filters
class AccountPostFilter(django_filters.FilterSet):
title = django_filters.CharFilter(lookup_expr='icontains')
category = django_filters.ChoiceFilter(choices=cat_list)
class Meta:
model = Post
fields = ['title', 'category']
views.py
class UserProfile(DetailView, MultipleObjectMixin):
model = Account
template_name = 'account/user_profile.html'
paginate_by = 5
def get_context_data(self, **kwargs):
posts = Post.objects.all().filter(author=self.kwargs['pk'])
context = super().get_context_data(object_list=posts, **kwargs)
context['filterset'] = AccountPostFilter(self.request.GET, queryset=posts)
return context
Thank you very much for your time. Best wishes, Daniel
There is another way of doing this, and do it in a clean and professional way, which will save you the trouble of using Django Filters:
Create a helper function called clean_filters (This will help you clean filters that come in from the brownser:
Create another help function called search (this will help you get the parameters from the GET request and put them in a **filters inside the django filter directive. And return them back with the paginator so you can keep the same filters when moving from page to page):
Here is your view (this simply calls the search function to reduce the code of your view and make it easy for your code to maintain):
Here is your HTML (just a classic pagination code for Django and Bootstrap. This also has the filter and the value of the filter in a loop inside the GET request):