0

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

  • Could you share the whole error message? – Dauros Mar 27 '23 at 09:19
  • TypeError at /search/ string indices must be integers Request Method: GET Request URL: http://127.0.0.1:8000/search/?page=2 Django Version: 4.1 Exception Type: TypeError Exception Value: string indices must be integers – Антон Нурапкин Mar 27 '23 at 10:28
  • So somehow `res.json()` is a string instead of a dict. Could you put a `print(res_json)` into the function and see what `res_json` really is? – Dauros Mar 27 '23 at 10:54
  • Also called type() res_json is res.json(): {'STATUS': 200, 'MESSAGES': [], 'RESP': [{'ARTID': '15584408', 'PARNR': '0', 'KEYZAK': 'MOV0006874', 'RVALUE': '10', 'RDPRF': '1', 'MINBM': '1.000', 'RETDAYS': '14', 'VENSL': '100.0', 'PRICE': '61.00', 'WAERS': 'RUB', 'DLVDT': '20230328120000', 'WRNTDT': '', 'ANALOG': '', 'PIN': 'BSG 65-230-005', 'BRAND': 'BSG', 'NAME': 'колпачок гайки колеса!черный\\ Opel Astra H/Astra G/Corsa C/Corsa D/Zafira B'}, ...]} – Антон Нурапкин Mar 27 '23 at 12:39

0 Answers0