Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not able to upload image in CRUD using serializers

I am doing CRUD using serializers as I am tasked.

In this context I am new to images and studied it,I have made files called ‘media’ to store images but I am getting an error like this
enter image description here

I have been trying to solve this error but didnt have much success

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

below is the insert function

def insert(request):
    data = {}
    if request.method == "POST":
        print('POST',id)
        data['categories'] = request.POST.get('categories')
        data['sub_categories'] = request.POST.get('sub_categories')
        data['color'] = request.POST.get('color')
        data['size'] = request.POST.get('size')
        data['title'] = request.POST.get('title')
        data['price'] = request.POST.get('price')
        data['sku_number'] = request.POST.get('sku_number')
        data['product_details'] = request.POST.get('product_details')
        data['quantity'] = request.POST.get('quantity') 
        data['image'] = request.FILES['images']
        form = POLLSerializer(data=data)
        print(form)
        if form.is_valid():
            print('form after valid:',form)
            print("error of form:",form.errors)
            form.save()
            
            messages.success(request, "Record Updated Successfully...!:)")
            return redirect("polls:show")
        else:
            print('form not valid')
            print(form.errors)
    if request.method == "GET":
        print('POST',id)
        category_dict = Categories.objects.filter(isactive=True)
        category = CategoriesSerializer(category_dict, many=True)
        sub_category_dict = SUBCategories.objects.filter(isactive=True)
        sub_category = SUBCategoriesSerializer(sub_category_dict,many=True)
        color_dict = Colors.objects.filter(isactive=True)
        color = ColorsSerializer(color_dict,many=True)
        size_dict = Size.objects.filter(isactive=True)
        size = SizeSerializer(size_dict,many=True)
        hm = {"context": category.data,"sub_context":sub_category.data,"color_context":color.data,"size_context":size.data}
        return render(request, "polls/product_insert.html", hm)

models

class Products(models.Model):
    categories = models.ForeignKey(Categories,on_delete=models.CASCADE)
    sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE)
    color = models.ForeignKey(Colors,on_delete=models.CASCADE)
    size = models.ForeignKey(Size,on_delete=models.CASCADE)
    image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True)
    title = models.CharField(max_length=50)
    price = models.CharField(max_length=10)
    sku_number = models.CharField(max_length=10)
    product_details = models.CharField(max_length=300)
    quantity = models.IntegerField(default=0)
    isactive = models.BooleanField(default=True)
    
def filepath(request,filename):
    old_filename = filename
    timeNow = datetime.datetime.now().start('%Y%m%d%H:%M:%S')
    filename = "%s%s" % (timeNow,old_filename)
    return os.path.join('uploads/',filename)

product_insert form

<form method="POST" enctype="multipart/form-data">
   {% csrf_token %}
            <table>
                <thead>
                    <tr>
                        <td>Categories</td>
                        <td>
                            <select name="categories" id="">
                                {% for c in context %}
                                   <option value="{{c.id}}">{{c.category_name}}</option>
                                {% endfor %}
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td>Sub-Categories</td>
                        <td>
                            <select name="sub_categories" id="">
                                {% for c in sub_context %}
                                   <option value="{{c.id}}">{{c.sub_categories_name}}</option>
                                {% endfor %}
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td>Colors</td>
                        <td>
                            <select name="color" id="">
                                {% for c in color_context %}
                                   <option value="{{c.id}}">{{c.color_name}}</option>
                                {% endfor %}
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td>Size</td>
                        <td>
                            <select name="size" id="">
                                {% for c in size_context %}
                                   <option value="{{c.id}}">{{c.size_name}}</option>
                                {% endfor %}
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td>Title</td>
                        <td>
                            <input type="text" name="title" placeholder="Enter title">
                        </td>
                    </tr>
                    <tr>
                        <td>Price</td>
                        <td>
                            <input type="text" placeholder="Enter the price" name="price">
                        </td>
                    </tr>
                    <tr>
                        <td>SKU Number</td>
                        <td>
                            <input type="text" name="sku_number">
                        </td>
                    </tr>
                    <tr>
                        <td>product_details</td>
                        <td>
                            <textarea name="product_details" cols="30" rows="10">

                            </textarea>
                        </td>
                    </tr>
                    <tr>
                        <td>quantity</td>
                        <td><input type="number" name="quantity" placeholder="Enter the quantity"></td>
                    </tr>
                    <tr>
                        <td>Product Image</td>
                        <td>
                            <input type="file" name="image">
                        </td>
                    </tr>

settings

STATIC_URL = 'static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]
MEDIA_ROOT = os.path.join(BASE_DIR,'media/')
MEDIA_URL = '/media/'

where am I going wrong in the code?

>Solution :

data['image'] = request.FILES['images']

It could be that you’re reading images instead of image from request.FILES, as to me it seems that data is initialized by the same keys of request.FILES .

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading