django upload view fails

Viewed 28

This is my Product model

class Product(models.Model):

name = models.CharField(max_length=255, blank=False)
category = models.ManyToManyField(ProductCategory)
thumbnail_image = models.ImageField(null=True, blank=True)
description = models.TextField(null=False, blank=False)
price = models.DecimalField(max_digits=20, decimal_places=2, null=False, blank=False)
stock = models.IntegerField(default=0)
tag = models.CharField(max_length=255, null=True, blank=True)
date = models.DateTimeField(auto_now=True)
enable = models.BooleanField(default=True)

as you can see category is many to many.

so I declared 'product.category.add(product_category)' in ProductUpload view

@api_view(['POST'])
def ProductUpload(request):

img = request.FILES.get('thumbnamil_image')
data = request.data
product_category = request.POST.getlist('category')
product = Product(name = data['name'],
    thumbnail_image = img,
    description = data['description'],
    price = data['price'],
    stock = data['stock'],
    tag = data['tag'],
    enable = data['enable']
    )


product.save()
product.category.add(product_category)
return Response('success')

I thought this is it to implement upload function. However,

it does not work..

if I declare POST method view in ProductList view, it works though..

if I erase the POST part of the ProductList, it is not working..

How I can integrate two seperated upload logics in ProductUpload view?

@api_view(['GET','POST'])
def ProductList(request):
if request.method == 'GET':
    products = Product.objects.all()
    serializer = ProductSerializer(products, many=True)
    return Response(serializer.data)       

elif request.method == 'POST':
    serializer = ProductSerializer(data=request.data, many=False)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data)
    
    return Response(serializer.errors) 
0 Answers
Related