Home > Enterprise >  django - React - Axios: Data not being saved in database
django - React - Axios: Data not being saved in database

Time:02-23

I am trying to create products through a react js component using axios post request.

In django log I see an OPTION request geting a 200 status code, but data not being saved in the DB.

When doing it through postman it is working fine, which makes me think the problem is in the axios request.

models.py

class Product(models.Model):
    title = models.CharField(max_length=32)
    notes = models.TextField()
    picture = models.ImageField(upload_to='product_images', null=True, blank=True)
    amount = models.IntegerField(default=0)

    @receiver(post_save, sender='product.Transaction')
    def update_amount(sender, **kwargs):
        product = Product.objects.get(title=kwargs['instance'].product)
        if kwargs['instance'].transaction_type == 'IN':
            product.amount  = kwargs['instance'].amount
            product.save()
        else:
            if product.amount - kwargs['instance'].amount > 0:
                product.amount = product.amount - kwargs['instance'].amount
                product.save()

    def __str__(self):
        return self.title

views.py

 class ProductCreateView(generics.CreateAPIView):
    serializer_class = ProductSerilizer
    permission_classes = (permissions.IsAuthenticated,)
    queryset = Product.objects.all() 

serializers.py

class ProductSerilizer(ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'

settings.py

ALLOWED_HOSTS = ['*']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'product',
    'rest_framework',
    'corsheaders',
    'rest_framework.authtoken'
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    ...
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
       'rest_framework.authentication.TokenAuthentication',
   ),
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ],
    'DATETIME_FORMAT': '%d-%m-%Y', 
}

    CORS_ALLOW_CREDENTIALS = True
    CORS_ALLOW_ALL_ORIGINS = True

AddProducts.js

import React, {useState} from 'react';
import axios from 'axios'
import { useNavigate } from "react-router-dom";

function AddProduct() {

    const [medicineTitle, setMedicineTitle] = useState('');
    const [description, setDescription] = useState('');
    const [medicineImage, setMedicineImage] = useState('');
    
    const navigate = useNavigate();

    const addToForm = async () => {

        let formfield = new FormData()

        formfield.append('title', medicineTitle)
        formfield.append('notes', description)
        formfield.append('picture', medicineImage)
        formfield.append('amount', 0)

        await axios({
            method: 'post',
            url: 'http://127.0.0.1:8000/api/protuct_create',
            headers: { 
                'Access-Control-Allow-Origin': '*',
                'Authorization': 'Token ********************************',
            },
            data: formfield,
           
            
        }).then((response) => {
            console.log(response);
          }, (error) => {
            console.log(error);
          });
        
    }

    return ( 
            <div className='container'>
                <h5>Agregar un medicamento</h5>
                <form encType='multipart/form-data' >
                    <div className="mb-3">
                        <label className="form-label">Nombre del medicamento</label>
                        <input 
                            type="text" 
                            className="form-control" 
                            id="title" 
                            aria-describedby="title"
                            placeholder='Introduce nombre del medicamentos'
                            name='title'
                            value={medicineTitle}
                            onChange={(e) => setMedicineTitle(e.target.value)} 
                        />
                    </div>
                    <div className="mb-3">
                        <label className="form-label">Descripci&oacute;n</label>
                        <textarea 
                            className="form-control" 
                            id="medicineDescription" 
                            placeholder='Introduce una descripci&oacute;n'
                            name="medicineDescription" 
                            aria-describedby="Description"
                            onChange={(e) => setDescription(e.target.value)}
                            >

                        </textarea>
                    </div>
                    <div className="mb-3">
                        <label className="form-label">Foto </label><br/>
                        <input 
                            type="file" 
                            className="form-control" 
                            id="image" 
                            aria-describedby="image"
                            placeholder='Selecciones la imagen'
                            name='image'
                            value={medicineImage}
                            onChange={(e) => setMedicineImage(e.target.value)} 
                        />
                    </div>
                    <button type="submit" className="btn btn-primary" onClick={addToForm}>Submit</button>
                </form>
            </div>
        
    );
}

export default AddProduct;
    

CodePudding user response:

I was able to figure this out.

The problems was related to CORS headers. I had to set the headers that are allowed by the API.

by adding the following code my settings.py in django backend, it allowed the request sent from the frontend:

CORS_ALLOW_HEADERS = [
    "accept",
    "accept-encoding",
    "authorization",
    "content-type",
    "dnt",
    "origin",
    "user-agent",
    "x-csrftoken",
    "x-requested-with",
]
  • Related