Search code examples
pythondjangodjango-views

POST request Parameters from Class based views - Pagination


I'm using Django's Pagination Module with class-based views.

My Queryset will contain 1000+ objects, which I need to display one by one and based on the content displayed.

I don't need to show previous pages, I just need to Accept/Reject and on both the clicks, it should paginate to the next page.

I need to update few fields in the database based on Accept/Reject clicked by the user. How can I get the POST request parameters from the template in my class-based view? so that I can perform different steps on the click of Accept/Reject

Here's my code:

#views.py

from django.views.generic import ListView
class DemoView2(ListView):
    
    model = MandateTable
    template_name = 'demo2.html'
    context_object_name = 'pg'
    paginate_by = 1
    queryset = MandateTable.objects.all()[:5] #For Testing purspose, working on only 5 objects

Template

<!--demo2.html-->

{% for mandates in pg %}
        <p>{{ mandates.FIELD_1 }}</p>
        <p>{{ mandates.FIELD_2 }}</p>
        <p>{{ mandates.FELD_3 }}</p>
        <p>{{ mandates.FIELD_4 }}</p>
        <p>{{ mandates.FIELD_5 }}</p>
    {% endfor %}

{% if is_paginated %}
      <ul class="pagination">
        {% if page_obj.has_previous %}
          <li><a href="?page={{ page_obj.previous_page_number }}">&laquo;</a></li>
        {% else %}
          <li class="disabled"><span>&laquo;</span></li>
        {% endif %}

<button value="Accept" name="btn-accept" class="btn btn-success btn-lg">
            {% if page_obj.has_next %}
                <a style="text-decoration: none" href="?page={{ page_obj.next_page_number }}">Accept</a>
            {% else %}
                <a style="text-decoration: none" href="{% url 'demo' %}">Accept</a>
            {% endif %}
        </button>

        <button value="Reject" name="btn-reject" class="btn btn-danger btn-lg">
            {% if page_obj.has_next %}
                <a style="text-decoration: none" href="?page={{ page_obj.next_page_number }}">Reject</a>
            {% else %}
                <a style="text-decoration: none" href="{% url 'demo' %}">Reject</a>
            {% endif %}
        </button>
      </ul>
{% endif %}

This is how my template is going to look

I'm new to class-based views with Pagination.

Appreciate all the help


Solution

  • This solution worked for me.

    main.js

        $("#btn_reject").click(function () {
            //Fetch few parameters and send it along with clicked button in AJAX request
            var mNum = $("#mNum")[0].getAttribute('data-mn');
            var data = {"btn_name": "APPROVE", "m_number": mNum};
            man_verification(data);
        });
    
        $("#btn_reject").click(function () {
            //Fetch few parameters and send it along with clicked button in AJAX request
            var mNum = $("#mNum")[0].getAttribute('data-mn');
            var data = {"btn_name": "REJECT", "m_number": mNum};
            man_verification(data);
        });
    
         function man_verification(data) {
            $.ajax({
                type: "POST",
                url: "/review/",
                data: data,
                success: function (data) {
                    //Code For Handlind Response Data
                },
                error: function (data) {
                    console.log("Error", data);
                },
                beforeSend: function (xhr, settings) {
                    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                        // Only send the token to relative URLs i.e. locally.
                        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
                    }
                }
            });
        }
    

    views.py

    class RevPageView(ListView):
        template_name = 'rev.html'
        queryset = db_query
    
        def get_context_data(self, *, object_list=None, **kwargs):
            context = super(RevPageView, self).get_context_data(**kwargs)
    
            try:
                #Get data from db
            paginator = Paginator(db_query, 1)
            page = self.request.GET.get('page')
            try:
                query = paginator.page(page)
            except PageNotAnInteger:
                query = paginator.page(1)
            except EmptyPage:
                query = paginator.page(paginator.num_pages)
            context['data'] = query
    
            return context
    
        def post(self, request, *args, **kwargs):
            data_status = None
            if request.is_ajax():
                get_pk = request.POST.get('mandate_number')
                m_status = request.POST.get('btn_name')
    
                #Make necessary changes to the db tables based on the received parameters
    
            data = {"data_status": data_status}
            return JsonResponse(data)
    

    If there's a better and efficient approach than this would like to know about it :)