gpt4 book ai didi

django - 上传有效图像。您上传的文件不是图片或损坏的图片

转载 作者:行者123 更新时间:2023-12-05 05:23:20 31 4
gpt4 key购买 nike

我收到以下错误:

{"image": ["Upload a valid image. The file you uploaded was either not an image or a corrupted image."]}

这是我的代码:

模型.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

序列化器.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))

表单.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 的新手,我不知道为什么会收到此错误。任何人都可以帮助我,在此先感谢。

最佳答案

我已经解决了这个问题。我保存了两次数据,这就是为什么我得到 {"image": ["Upload a valid image. The file you uploaded was either an image or a corrupted image."]} 问题。我只是删除了“item.save()”。工作正常...

谢谢

关于django - 上传有效图像。您上传的文件不是图片或损坏的图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37967661/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com