2016-06-22 83 views
2

我收到以下錯誤:上傳有效的圖片。您上傳的文件是不是沒有圖像或損壞的圖像

{"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休息的框架,我有不知道爲什麼我得到這個錯誤。 任何人都可以幫助我,在此先感謝。

+0

這不會有什麼什麼關係DRF,該錯誤是由您的形式是純粹的Django的到來。 –

+0

請詳細說明我的錯誤.. – neelima

回答

0

我修復了這個問題。我正在保存數據兩次,這就是爲什麼我得到{「image」:[「上傳一個有效的圖像。您上傳的文件不是圖像或損壞的圖像。」]}問題。我只是刪除了「 item.save()」。做工精細...

感謝

相關問題