Tips on converting Django model into desired format for Bootstrap-tables plugin integration

I want to integrate the bootstrap-table plugin with server-side functionality using Django Rest Framework to populate the data on the table. However, I keep getting the message "No matching records found". After some investigation, I discovered that a specific format is required for the plugin to function properly (as outlined in the documentation: Note that the server response format varies depending on whether the 'client' or 'server' option is specified. Examples can be found here: Without server-side pagination, With server-side pagination). In my case, this is the code I am currently using:

1) serializers.py

from rest_framework import serializers
from .models import Datos   

class DatosSerializer(serializers.ModelSerializer):
    class Meta:
        model = Datos            
        fields = (
            'loteInsp',
            'descripcion',
            'fecha',
            'material',
            'batch',
            'acepRech',
            'resultado',
            'limiteInferior',
            'target',
            'limiteSuperior',
            )

2) views.py

from rest_framework import generics
from .models import Datos
from .serializers import DatosSerializer

class DatosViewSet(generics.ListAPIView):
    queryset = Datos.objects.all().order_by('fecha')
    serializer_class = DatosSerializer

3) urls.py

 path('json/', DatosViewSet.as_view(), name='json'),

However, the server response that I receive looks like this in the console:

callback({"count":1064,"next":"http://127.0.0.1:8000/datos/json/?format=jsonp&limit=10&offset=0&order=asc&page=2&search=","previous":null,"results":[{"loteInsp":40004129308,"descripcion":"ALCANFOR P/P","fecha":"2015-01-03","material":15131132,"batch":"50602709L0","acepRech":true,"resultado":4.9,"limiteInferior":4.73,"target":5.26,"limiteSuperior":5.79},{"loteInsp":40004129308,"descripcion":"AC. DE EUCALIPTO P/P","fecha":"2015-01-03","material":15131132,"batch":"50602709L0","acepRech":true,"resultado":1.29,"limiteInferior":1.24,"target":1.33,"limiteSuperior":1.46},...

What modifications do I need to make to the serializer (or other components) to ensure that the response aligns with the required format for bootstrap-tables?

For example:

{
  "total": 800,
  "totalNotFiltered": 800,
  "rows": [
    {
      "id": 0,
      "name": "Item 0",
      "price": "$0"
    },
    {
      "id": 1,
      "name": "Item 1",
      "price": "$1"
    },
    {
      "id": 2,
      "name": "Item 2",
      "price": "$2"
    },
        ]
    }

Thank you in advance for any suggestions or ideas.

Answer №1

After some experimentation, I managed to get bootstrap-table to successfully read the data by making adjustments to the view DatosViewSet:

from rest_framework.response import Response
from rest_framework.decorators import api_view

@api_view(['GET',])
def api_view_set(request):
    if request.method=='GET':
        datos = Datos.objects.all().order_by('fecha')
        serializer = DatosSerializer(datos, many=True)
        return Response(serializer.data)

In the urls.py file:

path('json2/', api_view_set, name='json2'),

By implementing these changes, Bootstrap-table is now able to load the data correctly when calling the URL with this line in the table header options:

data-url="{% url 'app:json2'%}"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an issue when trying to submit the form - "Cannot POST /public/register-controller

I am currently working on developing a login/signup system using Express.js, MySQL, and Node.js. However, I encountered an error when I clicked on the submit button: Cannot POST /public/register-controller This is my index.html: <!DOCTYPE html> ...

Top tips for seamless image transitions

Currently working on a slideshow project and aiming to incorporate smooth subpixel image transitions that involve sliding and resizing, similar to the Ken Burns effect. After researching various techniques used by others, I am curious to learn which ones ...

How can I identify the blur or focusout event in a tinyMCE textarea?

I have been tackling with an existing project. Whenever I click on some editable text within the webpage, it transforms into a textarea and shows the tinyMCE toolbar. However, when I click outside of that textarea, the toolbar disappears. I am trying to fi ...

The functionality of triggers is not applicable to content that is dynamically loaded through ajax requests

I encountered a problem recently that required me to rewrite some functions. The original code looked like this: $('#type_of').on('change', function () { However, due to issues with manipulating the DOM and loading content via ajax, I ...

Insufficient data in the POJO class causing Android retrofit to encounter missing fields

Currently, I am utilizing Retrofit to retrieve data from an API and transform it into a POJO object. Regrettably, the API lacks documentation, making it unclear what information is contained within the JSON. Although I have fields in my POJO for the anti ...

Fetching information from a JSON source and storing it within an array of

I am currently facing an issue where I am unable to assign Exercise[] to Exercise. My goal is to retrieve data from a file, create a class object with the JSON values, and then add it to the class array to display as hardcoded JSON data. As someone who i ...

Strategies for deploying on production as you develop a fresh Nuxt application

What are some recommended strategies for deploying a Vue/Nuxt project on production, especially for larger applications with lengthy build times? Typically, running the command npm run build Causes the app to be inaccessible to users until the build proc ...

Error: Unable to locate module './clock' in the directory '/home/n/MyWork/my-app/src'

Upon attempting to start up the project, I encountered an error message stating: "Module not found: Can't resolve './clock' in '/home/n/MyWork/my-app/src'" The structure of the project is as follows: My-app --node-modules --public ...

The error property is not found in the type AxiosResponse<any, any> or { error: AxiosError<unknown, any>; }

As a beginner with typescript, I am encountering some issues with the following code snippet import axios, { AxiosResponse, AxiosError } from 'axios'; const get = async () => { const url = 'https://example.com'; const reques ...

Customize the Color of Your Material-UI Drawer

Need help with setting the background color of a Material-UI Drawer. I tried using the following code but it didn't work: const styles = { paper: { background: "blue" } } After defining the styles, I passed them to the Drawer component like ...

Tips for enabling simultaneous input focus on both TextField and Popover components

I am working on a popover component that appears below a textfield component. The goal is to trigger a menu when the user types a specific key, like :, into the textfield. The user can then select an option from this menu to autocomplete the textfield. A ...

Limiting the ability to pan to a single globe within the Google Maps API

I need help with restricting panning on a Google Maps API map to just one globe. By default, the map allows continuous panning east/west, causing it to repeat endlessly. I found a solution by henningj in response to this question var allowedBounds = new g ...

Display/Conceal WP Submenu

Struggling to switch the behavior of my Wordpress menu. Want it to display when clicked, not when hovered: <nav> <ul> <li> <?php wp_nav_menu( array( 'theme_location' => 'header-menu' ) ); ...

Surprising automatic scrolling upon pressing the keydown button in Bootstrap

My webpage appears normal with the Bootstrap framework, but whenever I press the down key, the screen scrolls down and displays unexpected white space due to reaching the end of the background-image sized at 1798px * 1080px. Please refer to the image: He ...

Adjust variable values when the window is resized

I've been working on getting some variable values to update when the window is resized. After researching, I learned that it's recommended to declare the variables outside of the .resize function scope and then try to change their values within ...

Unable to get the div to properly follow when scrolling, even when using the fixed position attribute

My webpage is divided into two sections - left and right. I've used divs to create the left navigation and right content. However, when scrolling down the page, only the right portion scrolls while the left navigation remains fixed. I'm looking ...

"Encountering issues with Rails and AJAX where the data returning is showing up

I am facing a challenge while trying to use AJAX in Rails to POST a comment without using remote: true. I am confused as to why my myJSON variable is showing up as undefined, while data is returning as expected. Check out my code below: function submitVi ...

Fluent-bit's TCP JSON parser specifically designed to handle large integers capped at 32-bit maximum

Consider the configuration file provided below: [INPUT] Name tcp Listen 0.0.0.0 Port 5170 Format json [OUTPUT] Name stdout Match * When running fluent-bit on Windows and sending the string {&qu ...

Initiate a unidirectional ajax request

My WCF service has a slow processing time when called for the first time, but caches the results in HttpRuntime.Cache afterwards. To initialize this cache, I want to initiate a fire-and-forget ajax call from JavaScript. Currently, my page contains the fol ...

How can I make an HTML button function with a JavaScript script?

When I click a button in an HTML file, it should trigger a function in a JavaScript file to display an alert that says "hey." However, this simple task is not working for me and I am unsure why. Java Script is enabled in my browser (Google Chrome) and I am ...