Triggering Django events from React Front End

Viewed 136

I am developing an inventory management system using a Django Backend and React Frontend linked with the Django REST API.

Currently I am able to make get and HTTP requests to the Django backend, for example my GET and POST requests are handled in the following code within customers/views.py file:

def Customers_list(request):
    if request.method == 'GET':
        data = Customer.objects.all()

        serializer = CustomerSerializer(data, context={'request': request}, many=True)

        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = CustomerSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(status=status.HTTP_201_CREATED)
            
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

The requests are made using axios, an example of this is shown here:

getCustomers = () => {
    axios.get(API_URL).then(res => this.setState({ customers: res.data }));
  };

Where the API_URL points to "http://localhost:8000/api/customers/"

My question is how would I allow more responses from the backend to my limited request types, for instance, I would like to have a button that increases the account age of all customers by 1, how could I implement this and other similar features where buttons trigger events in the django backend?

1 Answers

It's been a few months and my system is now fully deployed. I was able to achieve this functionality by passing specific data to the API from the front end, and using if/else statements on the Django backend. Django also makes it easy to create new views with different API URLs which can be used to separate the flow of data and simplify the view code into smaller chunks.

Related