Home > database >  How change filter variable in view from Django template?
How change filter variable in view from Django template?

Time:10-13

I have review model that has reviews made by users. In view I do pagination for it. Then I do filter the reviews by variable type = 'art' How i can change variable filter for type = 'music' from template to display selectet reviews? How then use all() to display all of them? Do I have to make separate templates for each view variable or is simpler way?

My view.py:

def viewrevs(request):
        rev = Reviews.objects.filter(type = 'art')
        paginator = Paginator(rev,2)
        page_number = request.GET.get('page')
        page_obj = paginator.get_page(page_number)
...

My template.html

{% for rev in page_obj %}
        {{ rev.name }}
        {{ rev.size }}
        {{ rev.data }}
...
{% enfor %}

CodePudding user response:

So you can use query paraments like this domain/search/?type=art

Your URL can be as such

urlpatterns = [
    path('domain/search/', views.CityListView.as_view()),
]

Then your views:

def viewrevs(request):
    # Grab the type from the query param
    _type = request.GET.get('type','art')
    
    # Filter by the type
    rev = Reviews.objects.filter(type=_type)
    paginator = Paginator(rev,2)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

You can even do similar for pagination, have a param for page_size and page

  • Related