Home > Blockchain >  django.db.utils.IntegrityError when sending post request with axios in vue
django.db.utils.IntegrityError when sending post request with axios in vue

Time:07-10

im new to web development so please explain your solution i am trying to send data to an endpoint in the api i created with the django rest framework in vue with axios but whenever i do i get this error : django.db.utils.IntegrityError: NOT NULL constraint failed: main_checkbox.label (i know im not building the api the way its supposed to be built but thats another problem) i can make a get request with axios no problem and i can even send post data via an html form with no problem (but i dont want to cause im creating a single page application with vue and don't want it to refresh when submitting) here is the vue code :

<template>
  <div >
    <input type="text" name="label" id="" v-model="label" />
    <input type="submit" value="Create" @click="createCheckbox" />
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      label: "",
    };
  },
  methods: {
    async createCheckbox() {
      let result = axios.post("http://127.0.0.1:8000/create/", {
        label: this.label,
      });
      console.log(result);
    },
  },
};
</script>

the django views code :

from rest_framework.response import Response
from rest_framework.decorators import api_view

from main.models import checkbox
from main.serializers import checkboxSerializer

@api_view(['POST'])
def create(request):
    checkboxobj = checkbox.objects.create(
        state=False, label=request.POST.get('label'))
    serialized = checkboxSerializer(checkboxobj)
    return Response(serialized.data)

django models :

from django.db import models

# Create your models here.


class checkbox(models.Model):
    label = models.CharField(max_length=50)
    state = models.BooleanField(default=False)

    def __str__(self):
        return self.label

django serializers :

from rest_framework.serializers import ModelSerializer

from main.models import checkbox


class checkboxSerializer(ModelSerializer):
    class Meta:
        model = checkbox
        fields = '__all__'

CodePudding user response:

One of the features of serializers is that it validates data the user sends to the server. ModelSerializer can fetch validated data and create a record if you use save() method after validation with is_valid(). So, in your views.py:

@api_view(['POST'])
def create(request):
    serializer = checkboxSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serialized.data)
    else:
        return Response(serializer.errors)

CodePudding user response:

As the error states, the issue is not that the POST request is failing. Rather the error is related to the database. When inserting the record with checkbox.objects.create. The label field is null while creating the record. It could be the front end is sending a null value for the label or there is an error parsing the value from the POST request.

Since you are using DRF, I would suggest using CreateAPIView, it will manage the parsing and inserting for you.

This should do the backend part:

class Checkbox(models.Model):
    label = models.CharField(max_length=50)
    state = models.BooleanField(default=False)

    def __str__(self):
        return self.label

class CheckboxSerializer(ModelSerializer):
    class Meta:
        model = Checkbox
        fields = '__all__'

class CreateCheckBox(CreateAPIView):
    serializer_class = CheckboxSerializer
  • Related