How to do pagination in Django? I have TypeError

49 views Asked by At

I want to do pagination on my site.

I do API-call to supplier's website. I get data, deserialize and save it in my model, then get those objects for view them. Also I get all unique names for query into model and I have error in that function. When I press "Next page" everything breaks.

Before pagination everything works.

view.py

def search(request):

    url_for_search = 'http://ws.armtek.ru/api/ws_search/search?format=json'
    template = 'profiles/search.html'

    if request.method == 'GET':
        
        # API-call
        searched = request.GET.get('searched')
        headers = { 'Authorization' : basic_auth(login, password)}
        params = {some_params}
        res = requests.post(url_for_search,headers=headers,data=params)

        if 200 <= res.status_code < 300 :
            
            # Deserialize
            serializer = ProfileSerializer(data=res.json()['RESP'],many = True)
            serializer.is_valid()
            serializer.save()

            # Getting data
            names = get_unique_names(res.json())
            number_products = len(res.json()['RESP'])
            products = Profile.objects.filter(NAME__in = names).distinct()[:number_products]

            # Pagination
            p = Paginator(Profile.objects.filter(NAME__in = names).distinct()[:number_products],10)
            page = request.GET.get('page')
            page_obj = p.get_page(page)

            return render(request, template, {"products":products,
                                              "page_obj":page_obj,
                                              'searched':searched})

        else:
            return HttpResponse('Error')

get_unique_names()

def get_unique_names(res_json):
    names = set([ item['NAME'] for item in res_json['RESP']])
    return names

ERROR in that line: names = set([ item['NAME'] for item in res_json['RESP']])

I dont want to do. Maybe I should do it with ListViev? but i don't sure, that it's gonna help

0

There are 0 answers