伙计们正在研究django-rest-framwork。现在我在(store_product)表创建一些新的记录,当我按下POST按钮提交新数据时,我收到此错误
为什么我会收到此错误? !!
ValueError at /store/
invalid literal for int() with base 10: ''
Request Method: POST
Request URL: http://localhost:8000/store/
Django Version: 2.0.1
Exception Type: ValueError
Exception Value:
invalid literal for int() with base 10: ''
Exception Location: /home/mohammadreza/www/html/academy/uenv/lib/python3.6/site-packages/django/db/models/fields/__init__.py in get_prep_value, line 947
Python Executable: /home/mohammadreza/www/html/academy/uenv/bin/python3
Python Version: 3.6.4
Python Path:
['/home/mohammadreza/www/html/academy/api/academy',
'/home/mohammadreza/www/html/academy/uenv/lib/python36.zip',
'/home/mohammadreza/www/html/academy/uenv/lib/python3.6',
'/home/mohammadreza/www/html/academy/uenv/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6',
'/home/mohammadreza/www/html/academy/uenv/lib/python3.6/site-packages']
Server time: Sun, 28 Jan 2018 11:54:13 +0330
INFO 这是我的serializer.py文件
from rest_framework import serializers
from .models import Product
class StoreSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = [
'product_id',
'author',
'category',
'title',
'description',
'filepath',
'created_date',
'updated_date',
]
read_only_fields = ['product_id', 'created_date', 'updated_date','author']
def validate_title(self,value):
qs = Product.objects.filter(title__iexact=value)
if self.instance:
qs.exclude(pk=self.instance.pk)
if qs.exists():
raise serializers.ValidationError("this title is already used")
return value
这是我的view.py文件
from rest_framework import generics
from .serializers import StoreSerializer
from .models import Product
class StoreCreateApiView(generics.CreateAPIView):
lookup_field = 'pk'
serializer_class = StoreSerializer
def get_queryset(self):
return Product.objects.all()
def perform_create(self, serializer):
serializer.save(author = self.request.user)
这是我的模型对象的模型
class Product(models.Model):
product_id = models.AutoField(primary_key=True, default='')
author = models.ForeignKey(User, on_delete=models.CASCADE,db_index=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, to_field='cat_id')
title = models.CharField(max_length=120)
description = models.TextField(null=True, blank=True)
filepath = models.CharField(max_length=100,null=True,blank=True)
created_date = models.DateTimeField(auto_now_add=True)
updated_date = models.DateTimeField(auto_now=True)
json :(将POST)
{ "类别":2, " title":" python new", " description":" new python", " filepath":"" }
答案 0 :(得分:1)
AutoField
看起来有问题。 AutoField为IntegerField,因此default=''
会引发错误,请删除此参数:
class Product(models.Model):
product_id = models.AutoField(primary_key=True)