Problems in React axios request to Django backend ( rest framework ) , Error 404 Not Found
I have created a backend with Django so that a user can subscribe to services provided by other users. If I add the user to another user's service list from Thunder, the request succeeds and the user is added, but if I try to do it from my react app it returns the error.
AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
code
:
"ERR_BAD_REQUEST"
config
:
{transitional: {…}, adapter: Array(3), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message
:
"Request failed with status code 400"
name
:
"AxiosError"
request
:
XMLHttpRequest
onabort
:
ƒ handleAbort()
onerror
:
ƒ handleError()
onload
:
null
onloadend
:
ƒ onloadend()
onloadstart
:
null
onprogress
:
null
onreadystatechange
:
null
ontimeout
:
ƒ handleTimeout()
readyState
:
4
response
:
"{\"affiliations\":[\"Expected a list of items but got type \\\"int\\\".\"]}"
responseText
:
"{\"affiliations\":[\"Expected a list of items but got type \\\"int\\\".\"]}"
responseType
:
""
responseURL
:
"http://127.0.0.1:8000/api/listofmembers/create/"
responseXML
:
null
status
:
400
statusText
:
"Bad Request"
timeout
:
0
upload
:
XMLHttpRequestUpload {onloadstart: null, onprogress: null, onabort: null, onerror: null, onload: null, …}
withCredentials
:
false
[[Prototype]]
:
XMLHttpRequest
response
:
{data: {…}, status: 400, statusText: 'Bad Request', headers: AxiosHeaders, config: {…}, …}
status
:
400
stack
:
"AxiosError: Request failed with status code 400\n at settle (http://localhost:5173/node_modules/.vite/deps/axios.js?v=1ddcf29b:1235:12)\n at XMLHttpRequest.onloadend (http://localhost:5173/node_modules/.vite/deps/axios.js?v=1ddcf29b:1566:7)\n at Axios.request (http://localhost:5173/node_modules/.vite/deps/axios.js?v=1ddcf29b:2124:41)\n at async addApplyPerson (http://localhost:5173/src/startcomponents/db/providers.js?t=1741726000120:200:22)\n at async http://localhost:5173/src/store/takorsend/thunks.js?t=1741726000120:172:22"
[[Prototype]]
:
Error
models.py
class ListOfMembers(models.Model):
#user = models.ForeignKey(User, on_delete=models.CASCADE)
#user = models.ManyToManyField(User, related_name='users', verbose_name='User')
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='users', verbose_name='User')
affiliations = models.ManyToManyField(Location, related_name='listofmembers', verbose_name='Location to Join')
#objects = ScheduleManager()
class Meta:
verbose_name = 'ListOfMember'
verbose_name_plural = 'ListOfMembers'
#Le decimos que en lugar de una objeto nos devuelva los valores de cada campo de forma visible, nos mostrara el nombre y apellido con separación
def __str__(self):
return f'{self.user } | {self.affiliations }'
admin.py
@admin.register(ListOfMembers)
class ListOfMembersAdmin(admin.ModelAdmin):
#model = User
list_display = (
'id',
'user',
'get_affiliations',
)
def get_affiliations(self, obj):
return ", ".join([str(affiliations.id) for affiliations in obj.affiliations.all()])
get_affiliations.short_description = 'Affiliation ID ( Location )'
#Le agregamos un buscador al admin y espesificamos que la busqueda sea en funcion al email o full_name
search_fields = ('id', 'affiliations')
serializer.py
class ListOfMembersSerializers(serializers.ModelSerializer):
class Meta:
model = ListOfMembers
#Si queremos mostrar todo lo definimos de la siguiente forma
fields = (
'id',
'user',
'affiliations',
)
views.py
#Permite guardar una fecha con el POST y agregando los atributos del modelo
class ListOfMembersCreate(CreateAPIView):
serializer_class = ListOfMembersSerializers
queryset = ListOfMembers.objects.all()
urls.py
from django.urls import path
from . import views
#Nombre para el conjunto de urls
app_name = "listofmembers_app"
urlpatterns = [
path(
'api/listofmembers/create/',
views.ListOfMembersCreate.as_view(),
),
path(
'api/listofmembers/total/',
views.ListOfMembersViews.as_view(),
),
path(
'api/listofmembers/my_list/<pk>/',
views.ListOfMembersViewsFromLocation.as_view(),
),
]
react.js
export const addApplyPerson = async( data ) => {
try {
const endpoint = 'api/listofmembers/create/';
const urlPOST = `${import.meta.env.VITE_API_URL}${endpoint}`;
console.log(urlPOST)
const payload = {
'user':4,
'affiliations':35,
}
//const resp = await axios.post(endpoint, payload);
const resp = await axios({
method: 'post',
url: urlPOST,
data: payload, // you are sending body instead
headers: {
// 'Authorization': `bearer ${token}`,
'Content-Type': 'application/json'
},
});
console.log(resp)
return {
ok: true
}
}
catch( error ) {
console.log(error)
return { ok: false, errorMessage: error.message, errorMessage2: error.response?.data.Error}
}
}
I have modified the code several times, but I can't get a new member from react, I tried to create with the other models and there is no problem, I think the problem is in the admin code that I had to implement to be able to receive the list of affiliated users with the user. I think the join part is the one that gives the problem.