Issue
I’m building a very simple react + django website. Everything was going fine until today I made some changes to both the backend and frontend to add a third app that displays dummy pictures with a description.
Up until that point, I was using axios to make get, post and delete requests with no trouble. I just wrote axios.post("api/", item) and it would post the item, or axios.delete(api/{props.id}
) and the item would be deleted.
Now, none of these work. At first I started getting 403 errors. Doing some troubleshooting, I tried adding the full url to see if it worked. Post worked. axios.post("localhost:8000/api/", item) now posts the item. The thing is that when I try to delete – axios.delete(localhost:8000/api/{props.id}
) -, I get a 301 error.
Besides kicking myself for not backing up before, what can I do? These are the backend and frontend codes.
Frontend:
import React, { useEffect, useState } from "react";
import Header from "./UI/Header";
import NewTask from "./tasks/NewTask";
import TaskList from "./tasks/TaskList";
import axios from "axios";
import classes from "./ToDo.module.css";
function ToDo(props) {
const [taskList, setTaskList] = useState([]);
const refreshList = async () => {
await axios.get("todo/").then((res) => {
const filteredData = res.data
setTaskList(filteredData);
});
};
useEffect(() => refreshList, []);
const addTaskHandler = async (title, description) => {
let item = {
title: title,
description: description,
completed: false,
};
await axios
.post(`todo/`, item)
.then((res) => {refreshList()})
.catch((err) => console.log(err));
};
const onCompleteHandler = async (item, id) => {
console.log(id)
await axios
.post(`/todo/${id}`, item)
.then(() => refreshList());
console.log('ToDo')
}
const onDeleteHandler = async (id) => {
await axios
.delete(`/todo/${id}`)
.then(() => {
refreshList()
})
};
return (
<div className={classes[props.display]}>
<Header></Header>
<NewTask onAdd={addTaskHandler}></NewTask>
<TaskList list={taskList} onDelete={onDeleteHandler} onComplete={onCompleteHandler}></TaskList>
</div>
);
}
export default ToDo;
Backend:
settings.py
...
"""
Django settings for backend project.
Generated by 'django-admin startproject' using Django 4.0.4.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'rest_framework',
'web',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.common.CommonMiddleware',
]
ROOT_URLCONF = 'backend.urls'
(…)
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# CORS whitelist for React server
CORS_ORIGIN_WHITELIST = [
'http://localhost:3000'
]
CORS_ALLOWED_ORIGINS = [
'http://localhost:3000'
]
CORS_ALLOW_METHODS = [
"DELETE",
"GET",
"OPTIONS",
"PATCH",
"POST",
"PUT",
]
# CORS_ALLOW_ALL_ORIGINS = True
CSRF_TRUSTED_ORIGINS = [
'http://localhost:3000',
]
urls.py
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from web import views
from django.conf.urls.static import static
from django.conf import settings
router = routers.DefaultRouter()
router.register(r'cars', views.CarView, 'car')
router.register(r'todo', views.ToDoView, 'todo')
router.register(r'dummy', views.DummyView, 'dummy')
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(router.urls)),
# path('/dummy/', './static/'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
from django.db import models
# Create your models here.
class Car(models.Model):
brand = models.CharField(max_length=250)
make = models.CharField(max_length=250)
plate = models.CharField(max_length=10)
year = models.IntegerField()
def __str__(self):
return self.brand + " " + self.plate
class ToDo(models.Model):
title = models.CharField(max_length=250)
description = models.CharField(max_length=500)
completed = models.BooleanField(default=False)
def __str__(self):
return self.title
class Dummy(models.Model):
name = models.CharField(max_length=250)
description = models.CharField(max_length=500)
pic = models.ImageField(
upload_to= 'images/', default='images/default.jpg')
def __str__(self):
return self.name
serializers.py
from rest_framework import serializers
from .models import Car, ToDo, Dummy
class CarSerializer(serializers.ModelSerializer):
class Meta:
model = Car
fields = ('id', 'brand', 'make', 'plate', 'year')
class ToDoSerializer(serializers.ModelSerializer):
class Meta:
model = ToDo
fields = ('title', 'description', 'completed', 'id')
class DummyPicSerializer(serializers.ModelSerializer):
class Meta:
model = Dummy
fields = ('name', 'description', 'pic', 'id')
views.py
from django.shortcuts import render
from django.http import HttpResponse
from rest_framework import viewsets
from .serializers import CarSerializer, ToDoSerializer, DummyPicSerializer
from .models import Car, ToDo, Dummy
# Create your views here.
def index(request):
return HttpResponse("Hello world. This works now!")
class CarView(viewsets.ModelViewSet):
serializer_class = CarSerializer
queryset = Car.objects.all()
class ToDoView(viewsets.ModelViewSet):
serializer_class = ToDoSerializer
queryset = ToDo.objects.all()
class DummyView(viewsets.ModelViewSet):
serializer_class = DummyPicSerializer
queryset = Dummy.objects.all()
Solution
I’ve just deleted all my migrations and database and redid the whole makemigrations-migrate deal with Django and suddenly it just works.
Maybe it had to do something with the way it was previously migrated? I’ll never know.
Answered By – Pedro Henestroza
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0