我收到以下错误:
{"image": ["Upload a valid image. The file you uploaded was either not an image or a corrupted image."]}
这是我的代码:
model.py
class products(models.Model):
product_name=models.CharField(max_length=100, blank=True)
price = models.IntegerField(null=True)
image = models.ImageField()
created = models.DateTimeField(default=timezone.now)
product_updated_date = models.DateTimeField(auto_now=True)
def __str__(self):
return self.product_name
serializers.py
class ProductSerializer(serializers.ModelSerializer):
image = serializers.ImageField(max_length=None, use_url=True)
class Meta:
model = products
fields = ('product_name', 'price', 'image', 'created', 'product_updated_date')
views.py
def addproduct(request):
if request.method == 'POST':
form = Addproductform(request.POST, request.FILES)
if form.is_valid():
name = request.POST.get("product_name")
price=request.POST.get("price")
image=form.cleaned_data['image']
item = products(image=image, product_name=name, price=price)
item.save()
serializer = ProductSerializer(data=form.cleaned_data)
if serializer.is_valid():
serializer.save()
return redirect('/task1')
return JsonResponse({'error': serializer.errors})
else:
form = Addproductform()
return render_to_response("add-product.html", {'form':form},
context_instance=RequestContext(request))
forms.py
class Addproductform(forms.Form):
error_css_class = "error"
product_name=forms.CharField(max_length=250, required=True, widget=forms.TextInput(attrs={'class': "form-control input-lg", "placeholder":'Product name'}))
price = forms.CharField(max_length=250,widget=forms.TextInput(attrs={'class': "form-control input-lg","placeholder":'Price'}))
image = forms.ImageField()
page1.html
<form action="#" enctype="multipart/form-data" method="post">
{% csrf_token %}
<div><label>Product Name</label></div><br>
<div>{{form.product_name}}</div>
<div style="color:red">{{form.product_name.errors}}</div><br>
<div><label>Price</label></div><br>
<div>{{form.price}}</div><br>
<div style="color:red">{{form.price.errors}}</div>
<div><label>Image</label></div><br>
<div>{{form.image}}</div>
<div style="color:red">{{form.image.errors}}</div>
<div class="product-option-shop" style="float:right">
<input type="submit" value="Submit" class="add_to_cart_button">
</div>
</form>
我是django rest-framework的新手,我不知道为什么会出现这个错误。 任何人都可以帮助我,提前谢谢。
答案 0 :(得分:0)
我已经解决了这个问题。我将数据保存两次,这就是为什么我得到 {&#34;图像&#34;:[&#34;上传有效图片。您上传的文件不是图片或图片已损坏。&#34;]} 问题。我只需删除&#34; item.save()&#34;。工作正常...
由于