Working with CSV files in a django-react app

sen
Level Up Coding
Published in
2 min readMay 11, 2021

--

Photo by Ferenc Almasi on Unsplash

Sometimes, you just don’t want (or need) a database model for all of your datasets — especially if they remain static. You may want to simply serve up some dataset to be used by the front end of your webapp / site. If you’re using react, you can’t slot your data into your render quite as easily as you would using a template model. Here is a short post illustrating how you can manage this simply when working with a django-react setup.

Option 1: Load directly into your React component

By far the simplest option. However, this involves loading your data directly into your frontend. Not ideal if you need to run some model or manipulation before serving up your dataset.

Simply add the following line to the imports in your React Component:

import data from "path-to-file"

The filepath here should be relative to the location of your component file. Note that you will require a csv loader to load csv files this way. I prefer to avoid this by working with json. To convert from csv to json using python’s pandas package:

import pandas as pddf = pd.read_csv('path-to-csv')
df.to_json('json-filename.json', orient='records')

Option 2: Create a View which loads your dataset and serves it to an API

This is my preferred route. In your ‘views.py’ file you can simply load your dataset into a pandas dataframe, convert to json and serve up the object as a response. Here’s a short snippet:

# views.pyimport pandas as pd
import json
from rest_framework.decorators import permission_classes
from rest_framework import permissions
from rest_framework.views import APIView
from rest_framework.response import Response
@permission_classes((permissions.AllowAny,))
class InsertReleventNameView(APIView):
def get(self, request, *args, **kwargs):
df = json.loads(pd.read_csv(“path-to-data-file”).to_json(orient=’records’))
return Response(df)#urls.pyfrom django.urls import path
from .views import InsertReleventNameView
urlpatterns += path(‘insert-your-url’, InsertReleventNameView.as_view())

Finally, to access your data through your React Component, simply fire off a fetch request (normally within a useEffect hook):

// inside your react functional component:const [data, setData] = useEffect();useEffect(() => {
const getData = async () => {
try {
const res = await axios.get(‘/insert-your-url’);
setData(res.data)
}
catch (err) {
}
}
getData();
}, []);

Here, I use the axios requests package to fetch my dataset from the api url and store my data in state. And now, I can do as I wish with my dataset without the hassle of setting up and loading into a database model.

Enjoy!

--

--