PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, September 10, 2022

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

 September 10, 2022     ajax, django, frontend, javascript, reactjs     No comments   

Issue

I'm currently working on a personal portfolio website using Django for the backend and database, and React for all the frontend stuff.

In this program, I have various fields that I would like to update every once in a while; I have Django tables for my education history, my work experiences, my skills, and a table to hold portfolio entries. I'd like to display this information on my React frontend, where I could display a page containing cards with all the portfolio projects I've created, and a page where my work experience, skills, and education history is all displayed.

Using plain Django, I would have simply selected the items from the table in views.py and passed it to the context, rendering the items as needed. With React, I don't know how I would handle such a request.

The way my code currently works, in the React components, I declare objects with the required fields such as

const myExperiences = [{
        name: "Company name",
        title: "job title",
        description: "job description",
        startDate: "start", 
        endDate: "end",
        location: "city, country",
    }]

and I display them by using the map function to put them in the desired format.

This is not ideal as it'd require me to change my source code any time I'd like to add more entries, where I would rather do it from Django admin console.

My other idea was to fetch the data from a Django API, but that seems inefficient, and having to fetch information from 3 different tables every time the page feels like it'd be slow for the user for no reason.

What is the right course of action here? What would you guys suggest?


Solution

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(`http://127.0.0.1:8000/api/lastpayrollruns/`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                 Authorization: `Token ${localStorage.getItem('token')}`
            },
        })
        .then(res => res.json())
        .then(data => {
          setPayrollRuns(data)
          });
    }, []);

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

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

    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>
        </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)

Note:

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.



Answered By - JSRB
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing