Connecting my Backend to my frontend

This is my first time using React so I used a tutorial for this. I keep encountering the page not found message. The URL worked for the React pages TransactionList and CreateTransaction but isn’t working for EditTransaction

This is my views.py

#Transaction API
class TransactionListCreateView(generics.ListCreateAPIView):
    queryset = Transaction.objects.all()
    serializer_class = TransactionSerializer

class TransactionDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Transaction.objects.all()
    serializer_class = TransactionSerializer
    lookup_field = 'id'

This is my urls.py

path('transactions/', TransactionListCreateView.as_view(), name='transaction-list-create'),

path('transactions/<int:id>/', TransactionDetailView.as_view(), name='transaction-detail'),

This my page for updating transactions

import React, { useEffect, useState } from "react";
import { Link, useNavigate, useParams } from "react-router-dom";



export default function EditTransaction() {

    const params = useParams()
    const [initialData, setInitialData] = useState()
    const [validationErrors, setValidationErrors] = useState({})

    const navigate = useNavigate()

    function getTransaction() {
        fetch("http://127.0.0.1:8000/transactions/" + params.id)
        .then(response => {
            if (response.ok) {
                return response.json()
            }

            throw new Error()
        })
        .then(data => {
            setInitialData(data)
        })
        .catch(error => {
            alert('Unable to read the Transaction details')
        })
    }

    useEffect(getTransaction, [params.id])

    async function handleSubmit(event) {
        event.preventDefault()

        const formData = new FormData(event.target)
        const Transaction = Object.fromEntries(formData.entries())

        if (!Transaction.name) {

                alert("Please fill the Name field")
                return
            }

            try {
                const token = '852de93b4848505296fb5fe56e41a6d1501adfca';


                const response = await fetch("http://127.0.0.1:8000/transactions/" + params.id, {
                    method: 'PATCH',
                    body: formData,
                    headers: {
                        'Authorization': `Token ${token}`
                    },
                });

                const data = await response.json()

                if(response.ok){
                    //Transaction Created Correctly!
                    navigate('/admin/transaction')
                }
                else if (response.status === 400){
                    setValidationErrors(data)
                }
                else(
                    alert('Unable to Update Transaction')
                )
            }
            catch(error) {
                alert('Unable to connect to the server')
            }
    }

    return(
        <div className="container my-4">
            <div className="row">
                <div className='col-md-8 mx-auto rounded border p-4'>
                    <h2 className= "text-center mb-5">Edit Transaction</h2>

                    <div className="row mb-3">
                            <label className='col-sm-4 col-form-label'>ID</label>
                            <div className= 'col-sm-8'>
                                <input readOnly className='form-control-plaintext' defaultValue={params.id}/>
                            </div>
                        </div>


                    {
                        initialData &&
                    <form onSubmit={handleSubmit}>
                        <div className="row mb-3">
                            <label className='col-sm-4 col-form-label'>Name</label>
                            <div className= 'col-sm-8'>
                                <input className='form-control' name='name' defaultValue={initialData.name}/>
                                <span className='text-danger'>{validationErrors.name}</span>
                            </div>
                        </div>

                        <div className="row mb-3">
                            <label className='col-sm-4 col-form-label'>Amount</label>
                            <div className= 'col-sm-8'>
                                <input className='form-control' name='amount' defaultValue={initialData.amount}/>
                                <span className='text-danger'>{validationErrors.amount}</span>
                            </div>
                        </div>

                        <div className="row mb-3">
                            <label className='col-sm-4 col-form-label'>Balance After Transaction</label>
                            <div className= 'col-sm-8'>
                                <input className='form-control' name='balance after transation' defaultValue={initialData.balanceaftertransaction}/>
                                <span className='text-danger'>{validationErrors.balanceaftertransaction}</span>
                            </div>
                        </div>

                        <div className="row mb-3">
                            <label className='col-sm-4 col-form-label'>Transaction Number</label>
                            <div className= 'col-sm-8'>
                                <input className='form-control' name='transaction number' defaultValue={initialData.transactionnumber}/>
                                <span className='text-danger'>{validationErrors.transactionnumber}</span>
                            </div>
                        </div>

                        <div className="row mb-3">
                            <label className='col-sm-4 col-form-label'>Description</label>
                            <div className= 'col-sm-8'>
                                <input className='form-control' name='description' rows= "4" defaultValue={initialData.description}/>
                                <span className='text-danger'>{validationErrors.description}</span>
                            </div>
                        </div>

                        <div className="row mb-3">
                            <label className='col-sm-4 col-form-label'>Currency</label>
                            <div className='col-sm-8'>
                                <select className='form-select' name='currency'>
                                    <option value='USD'>USD</option>
                                    <option value='EUR'>EUR</option>
                                    <option value='GBP'>GBP</option>
                                    <option value='JPY'>JPY</option>
                                    <option value='CNY'>CNY</option>
                                    <option value='CAD'>CAD</option>
                                    <option value='INR'>INR</option>
                                    <option value='CHF'>CHF</option>
                                    <option value='ZAR'>ZAR</option>
                                    <option value='MXN'>MXN</option>
                                    <option value='BRL'>BRL</option>
                                    <option value='KRW'>KRW</option>
                                    <option value='RUB'>RUB</option>
                                    <option value='SAR'>SAR</option>
                                    <option value='NGN'>NGN</option>
                                    <option value='SGD'>SGD</option>
                                    <option value='PHP'>PHP</option>
                                    <option value='BTC'>BTC</option>
                                    <option value='ETH'>ETH</option>
                                    <option value='USDT'>USDT</option>
                                    <option value='USDC'>USDC</option>
                                    <option value='BNB'>BNB</option>
                                    <option value='XRR'>XRR</option>
                                    <option value='LTC'>LTC</option>
                                    <option value='AUD'>AUD</option>
                                    <option value='SOL'>SOL</option>
                                    <option value='XMR'>XMR</option>
                                    <option value='XOF'>XOF</option>
                                    <option value='XAF'>XAF</option>
                                    <option value='XCD'>XCD</option>
                                </select>
                                <span className='text-danger'>{validationErrors.currency}</span>
                            </div>
                        </div>

                        <div className="row mb-3">
                            <label className='col-sm-4 col-form-label'>Transaction Type</label>
                            <div className='col-sm-8'>
                                <select className='form-select' name='transaction type'>
                                    <option value='deposit'>Deposit</option>
                                    <option value='deposit'>Direct Deposit</option>
                                    <option value='deposit'>Refund</option>
                                    <option value='deposit'>Withdrawal</option>
                                    <option value='deposit'>Payment</option>
                                    <option value='deposit'>Purchase</option>
                                    <option value='deposit'>Fee</option>
                                    <option value='deposit'>Internal Transfer</option>
                                    <option value='deposit'>External Transfer</option>
                                    <option value='deposit'>P2P Transfer</option>
                                    <option value='deposit'>Reversal</option>
                                    <option value='deposit'>Loan Disbursement</option>
                                    <option value='deposit'>Loan Payment</option>
                                    <option value='deposit'>Buy</option>
                                    <option value='deposit'>Sell</option>
                                    <option value='deposit'>Dividend</option>
                                    <option value='deposit'>Recurring Payment</option>
                                    <option value='deposit'>Automatic Transfer</option>
                                </select>
                                <span className='text-danger'>{validationErrors.transactiontype}</span>
                            </div>
                        </div>

                        <div className="row mb-3">
                            <label className='col-sm-4 col-form-label'>Transaction Status</label>
                            <div className='col-sm-8'>
                                <select className='form-select' name='transaction status'>
                                    <option value='deposit'>Pending</option>
                                    <option value='deposit'>Completed</option>
                                    <option value='deposit'>Failed</option>
                                    <option value='deposit'>Reversed</option>
                                    <option value='deposit'>Cancelled</option>
                                    <option value='deposit'>Refunded</option>
                                    <option value='deposit'>In Progress</option>
                                    <option value='deposit'>On hold</option>
                                    <option value='deposit'>Authorized</option>
                                    <option value='deposit'>Disputed</option>
                                    <option value='deposit'>Expired</option>
                                    <option value='deposit'>Processing</option>
                                    <option value='deposit'>Scheduled</option>
                                    <option value='deposit'>Partially Completed</option>
                                    <option value='deposit'>Settled</option>
                                </select>
                                <span className='text-danger'>{validationErrors.transactionstatus}</span>
                            </div>
                        </div>

                        <div className='row'>
                            <div className='offset-sm-4 col-sm-4 d-grid'>
                                <button type='submit' className='btn btn-primary'>Submit</button>
                            </div>
                            <div className='col-sm-4 d-grid'>
                                <Link className='btn btn-secondary' to='/admin/transaction' role='button'>Cancel</Link>
                            </div>
                        </div>

                    </form>
                    }
                </div>
            </div>
        </div>
    )
}

A guess, because I know little about React: should the URL here end in a / to match the one in your urls.py:

You should check the console for errors. “Doesn’t work” is not very actionable.

I got an error 404. I’m not sure if I’m connecting to my django server the right way.

Yeah I put it like this

fetch("http://127.0.0.1:8000/transactions/" + params.id + "/")

It still didn’t work

Do you think Axios is best if I’m trying to create the CRUD application? Especially because I am having trouble with what I am doing right now.

What is the url used in the request that’s getting the 404? i.e., from your Django logs, or the Network tab of your browser’s web developer tools.

The url i used is “http://127.0.0.1:8000/transactions/

Is that the url that is getting the 404? Or is it something more like http://127.0.0.1:8000/transactions/4/ (the url with the <id> parameter).

What is the actual and specific url that is showing in your runserver log as returning the 404?

Side note: Use single backticks - ` around url strings to keep them from being interpreted by the forum as links - as I did in the reference here.

I tested http://127.0.0.1:8000/transactions/14/ and it worked. I can use the PUT, Patch, and Delete method on that one. I was testing to the url with at the end. But now I need know how I can update and delete any transaction instead of just one.

You update any specific transaction by submitting the changes to the url constructed with the appropriate id parameter.

1 Like