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:
JavaScript
x
2
1
{'color_name': [ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')]}
2
below is the insert and show function that I have tried out
JavaScript
1
29
29
1
def show_colors(request):
2
showcolors = Colors.objects.filter(isactive=True)
3
print(showcolors)
4
serializer = ColorsSerializer(showcolors,many=True)
5
print(serializer.data)
6
return render(request,'polls/show_colors.html',{"data":serializer.data})
7
8
def insert_colors(request):
9
if request.method == "POST":
10
insertcolors = {}
11
insertcolors['color_name']=request.POST.get('color_name')
12
insertcolors['color_description']=request.POST.get('color_description')
13
form = ColorsSerializer(data=insertcolors)
14
if form.is_valid():
15
form.save()
16
print("hkjk",form.data)
17
messages.success(request,'Record Updated Successfully...!:)')
18
return redirect('colors:show_colors')
19
else:
20
print(form.errors)
21
return redirect('colors:show_colors')
22
else:
23
insertcolors = {}
24
form = ColorsSerializer(data=insertcolors)
25
if form.is_valid():
26
print(form.errors)
27
return render(request,'polls/insert_colors.html')
28
29
model
JavaScript
1
5
1
class Colors(models.Model):
2
color_name = models.ForeignKey(Products, on_delete=models.CASCADE,default=None)
3
color_description = models.CharField(max_length=10)
4
isactive = models.BooleanField(default=True)
5
HTML of insert_color
JavaScript
1
15
15
1
<tr>
2
<td>Colors Name</td>
3
<td>
4
<input type="text" name="color_name" placeholder="COLORS">
5
</td>
6
</tr>
7
<tr>
8
<td>Colors Description</td>
9
<td>
10
<textarea name="color_description" id="" cols="30" rows="10">
11
12
</textarea>
13
</td>
14
</tr>
15
HTML of show color
JavaScript
1
3
1
<td><b>{{result.color_name}}</b></td>
2
<td><b>{{result.color_description}}</b></td>
3
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.