[Django]-How would I render data from a Django model with a React frontend?



As requested please find below a basic common approach with a React / Django setup:

  1. Make an (async) API request in React to your Django endpoint/view (in this case Iโ€™m using standard fetch API)
  2. Map the returned JSON to create DOM elements for rendering
import PayrollRuns from "./PayrollRuns";
import PayrollDetails from "./PayrollDetails";
import {useEffect, useState} from "react";
import moment from "moment";

const PayrollWrapper = () => {

    // Set State for Payroll data
    const [payrollRuns, setPayrollRuns] = useState([])

    // Fetch data --> 1.)
    useEffect(() => {

        // Fetch the Payroll Data related to the logged in User
        fetch(``, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                 Authorization: `Token ${localStorage.getItem('token')}`
        .then(res => res.json())
        .then(data => {
    }, []);

    // --> 2.)
    const runItems = props.payrollRuns.map((run) =>
        <div key={run.id} className="flex justify-between p-2 text-lg text-base">
                {moment(run.month.period).format('YYYY MMMM')}:
                Paid {run.payroll_run_items.length} talents

                {run.payroll_run_items.reduce((acc, value) => {
                  return parseFloat(value.amount.toFixed(2)) + acc; // Add 'value.amount' to 'acc'
                }, 0)}

    return (
        <div className="runs-wrapper bg-white rounded-xl h-full w-48 shadow-sx-shadow p-4 flex flex-col">
            <h1 className="border-b-2 pb-4">Payroll Runs</h1>
            <div className="grow overflow-auto p-4">{runItems}</div>

export default PayrollWrapper

Django API endpoint/view for the given example:

class PayrollRun(APIView):
    Retrieve payroll runs including line items for a company
    def get(self, request):
        company = Company.objects.get(userprofile__user=request.user)
        payroll_runs = Payroll.objects.filter(company=company).order_by('-month')
        serializer = PayrollSerializer(payroll_runs, many=True)

        return Response(serializer.data)


One key concept of this setup is to provide the authentication header (token) for the API request as you will want to access the Django authenticated user (request.user) object in your views to make the database queries according to the user on client side.


Leave a comment