1

I'm using Django and React for a project that consumes Trello's API. I created functions in django views.py that will get user's boards, lists and cards. The problem is, to get a list, I need that the user select a board, because the list's endpoint requires a board id (and so on). I can show the user's boards on my react page and storage the board's id on a variable in Index.js (on pages folder), but I have no ideia how I can send the selected board id to views.py to consume Trello's api according to the user's selected board. Here's my code.

Django views.py:

from rest_framework.decorators import api_view
from rest_framework.response import Response
from dotenv import load_dotenv
from treegia.settings import TRELLO_URL
import os
import requests

load_dotenv()
TRELLO_KEY = os.getenv('TRELLO_KEY')
TRELLO_TOKEN = os.getenv('TRELLO_TOKEN')


@api_view(['GET'])
def get_boards(request):
    if request.method == 'GET':
        board_endpoint = TRELLO_URL+'members/me/boards'
        jsonObj = {'fields':'name,id', 'key':TRELLO_KEY, 'token':TRELLO_TOKEN}        
        boards = requests.get(board_endpoint, json=jsonObj).json()
        return Response(boards)


@api_view(['GET'])
def get_lists(request):
    if request.method == 'GET':
        list_endpoint = TRELLO_URL+ 'boards/' + id_board + '/lists'
        jsonObj = {'fields':'name,id', 'id':id_board, 'key':TRELLO_KEY, 'token':TRELLO_TOKEN}
        lists = requests.get(list_endpoint, json=jsonObj).json()
        return Response(lists)


@api_view(['GET'])
def get_cards(request):
    if request.method == 'GET':
        card_endpoint = TRELLO_URL+ 'lists/' + id_list + '/cards'
        jsonObj = {'fields':'name,id', 'id':id_list, 'key':TRELLO_KEY, 'token':TRELLO_TOKEN}        
        cards = requests.get(card_endpoint, json=jsonObj).json()
        return Response(cards)

React Index.js:

import React from 'react';
import Navbar from '../components/Navbar';
import '../styles/index.css'

const Index = () => {
    const [boards, setBoards] = React.useState([]);
    const [boardId, setBoardId] = React.useState([]);

    const [lists, setLists] = React.useState([]);
    const [listId, setListId] = React.useState([]);



    React.useEffect(() => {
        getBoards();
    }, []);

    React.useEffect(() => {
        getLists();
    }, []);


    async function getBoards() {
        await fetch('http://localhost:8000/boards/')
            .then(resp => resp.json())
            .then(data => {
                console.log(data);
                if(data) setBoards(data);
            })
    }

    async function getLists() {
        await fetch('http://127.0.0.1:8000/lists/')
            .then(resp => resp.json())
            .then(data => {
                console.log(data);
                if(data) setLists(data);
            })
    }


    return (
        <div id='index-page'>
            <Navbar />
                <div className='boards'>
                    <h1>Your boards</h1>
                    <div className='boards-container'>
                    {boards.map(board => (
                            <button key={board.id} onClick={() => {
                                setBoardId(board.id)
                            }}>{board.name}</button>
                            ))}
                            </div>
                </div>

                <div className='lists'>
                    <h1>Your lists</h1>
                    <div className='lists-container'>
                    {lists.map(list => (
                            <button key={list.id} onClick={() => {
                                setListId(list.id)
                            }}>{list.name}</button>
                            ))}
                            </div>
                </div>
            {boardId ? <p>{boardId}</p> : ''}
            {listId ? <p>{listId}</p> : ''}
        </div>
    );
}


export default Index;

Basically, when the user selects a board, I what to send the id to get_lists function. Is this possible to do?

5
  • Hi there. Dont you think that django rest framework would be better for this task? Commented Jan 23, 2022 at 5:04
  • Hi @EliasPrado. You know, I'm really n00b about back-end, so at this beginning I don't actually know where django and django rest framework differ. I'm thiking that I'll build an API that consumes Trello's API, use another API to post those information and I'll have a front-end to select what infos will be posted. But where and how I'll use one or another, it's a little bit foggy for me. Commented Jan 25, 2022 at 17:59
  • Alright, Django as you know is a python framework and django-rest-framework is a rest-api framework accoupled on Django. To be honest django rest framework is an imrprovement of Django's serialization. They are two but they work together. Therefore, when you set the work environment to create a rest api you need to first install django then install django-rest-framework. As a result, django-rest-framework does not work without Django. In addition, again, what django-rest will do is only improve Django's power to create REST APIs. Commented Jan 25, 2022 at 18:58
  • I read an article explaining the difference, but only now I understood. Thank you so much. But why did you suggest I'd use drf? Am I not using it with this code? Commented Jan 25, 2022 at 19:25
  • Well, not really. You need to use serializers and viewset classes. But this way I have never seen working with drf for about two years. Commented Jan 25, 2022 at 19:56

1 Answer 1

1

In the view

def get_lists(request):
   print(request.query_params['id_list']) # 'id_list being the variable you want to pass from the front end

this sets that we are expecting a parameter from the front end get request. Remember to add a try catch arround it..cos if that query_param doesnt exist it will throw and erroe.

Non in the FE.. while making a request, set request parameter 'id_list = '


var url = new URL('http://127.0.0.1:8000/lists')

var params = {id_list:'3'} // or whatever the params

url.search = new URLSearchParams(params).toString();

fetch(url);

Essentially you add the query params to the request url like

http://127.0.0.1:8000/lists/?id_list=3&another_param=2..

test the backend using postman or smthn before integration..to make sure the correct url and stuff.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey dude, I forgot to thank you, but it did work, thanks a lot! Now, I can only access my list view on json if I manually type the parameter at the url. I'd like to do this automatically, but anyways, my bigger problem was solved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.