[Answer]-What is the best way to implement Query Form in Django ListView?

1👍

Last week I faced the similar problem. My model was a common django User. However the same approach can be used here.

I guess you want to search through your Inscriptions using search field and paginating your results. And when you go through the pages you expect to see the results of your search query.

Your models.py stays as it is. We are going to modify forms.py as it will be able to initialize the search request

class InscriptionQueryForm(forms.Form):
query_inscription = forms.CharField(label='Code', required=False)

def __init__(self, query_inscription):
    super(InscriptionQueryForm, self).__init__()
    self.fields['query_inscription'].initial = query_inscription

Now let’s look at the views.py. You don’t need to store your request value in the session as schillingt mentioned in his comment. All you need is to init your form with the search request.

class InscriptionListView(ListView):
model = Inscription
paginate_by = 4
context_object_name = 'inscriptions'
query_inscription = ''

def get_context_data(self, **kwargs):
    context = super(InscriptionListView, self).get_context_data(**kwargs)
    context['form'] = InscriptionQueryForm(self.query_inscription)
    # this parameter goes for the right pagination
    context['search_request'] = ('query_inscription=' +
                                 unicode(self.query_inscription))
    return context

def get(self, request, *args, **kwargs):
    self.query_inscription = request.GET.get('query_inscription', '')
    return super(InscriptionListView, self).get(request, *args, **kwargs)

def get_queryset(self):
    if not self.query_inscription:
        inscription_list = Inscription.objects.all()
    else:
        inscription_list = Inscription.objects.filter(
            code__icontains=self.query_inscription)

    return inscription_list.order_by('-active')

And the last thing to mention is the pagination
inscription_list.html

<form action="">
{{ form.as_p }}
<input type="submit" value="search"/>
</form>
<hr/>
{% if inscriptions %}
    {% for inscription in inscriptions %}
        {{ inscription.code }} {{ inscription.start_on }} {{ inscription.finish_on }}
        <hr/>
    {% endfor %}
    {% if is_paginated %}
        <div class="pagination">
            <span class="page-links">
                {% if page_obj.has_previous %}
                    <a href="?{{ search_request }}&page={{ page_obj.previous_page_number }}">previous</a>
                {% endif %}
                <span class="page-current">
                    Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
                </span>
                {% if page_obj.has_next %}
                    <a href="?{{ search_request }}&page={{ page_obj.next_page_number }}">next</a>
                {% endif %}
            </span>
        </div>
    {% endif %}
{% endif %}

That’s it!

Leave a comment