Skip to content
Advertisement

Not able to do Insert operation in CRUD

I am making a CRUD of colors with color_name and color_description. While trying to insert the details the error below has be shown:

{'color_name': [ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')]}

below is the insert and show function that I have tried out

def show_colors(request):
    showcolors = Colors.objects.filter(isactive=True)
    print(showcolors)
    serializer = ColorsSerializer(showcolors,many=True)
    print(serializer.data)
    return render(request,'polls/show_colors.html',{"data":serializer.data})

def insert_colors(request):
    if request.method == "POST":
        insertcolors = {}
        insertcolors['color_name']=request.POST.get('color_name')
        insertcolors['color_description']=request.POST.get('color_description')
        form = ColorsSerializer(data=insertcolors)
        if form.is_valid():
            form.save()
            print("hkjk",form.data)
            messages.success(request,'Record Updated Successfully...!:)')
            return redirect('colors:show_colors')
        else:
            print(form.errors)
            return redirect('colors:show_colors')
    else:
        insertcolors = {}
        form = ColorsSerializer(data=insertcolors)  
        if form.is_valid(): 
            print(form.errors)   
        return render(request,'polls/insert_colors.html')

model

class Colors(models.Model):
    color_name = models.ForeignKey(Products, on_delete=models.CASCADE,default=None)
    color_description = models.CharField(max_length=10)
    isactive = models.BooleanField(default=True)

HTML of insert_color

<tr>
  <td>Colors Name</td>
  <td>
    <input type="text" name="color_name" placeholder="COLORS">
  </td>
</tr>
<tr>
  <td>Colors Description</td>
  <td>
    <textarea name="color_description" id="" cols="30" rows="10">

    </textarea>
  </td>
</tr>

HTML of show color

<td><b>{{result.color_name}}</b></td>
<td><b>{{result.color_description}}</b></td>

I have checked the names assigned and they are matching, so where am I going wrong?

Advertisement

Answer

according to your model, the color_name is a foreign key but somehow your request seems to be sending a string instead of int, which is causing a mismatch there.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement