0

I am working on an e-commerce project, and I want to add products from the front end. The files in my product app in Django is as follows this is my model.py:

 class Product(models.Model):
        pub_date = models.DateTimeField(default=datetime.now)
        price = models.DecimalField(max_digits=100000,decimal_places=5,null=False,blank=False)
        device_name = models.CharField(max_length = 50, null=True)
        photo = models.ImageField(upload_to = 'product_photos/%y/%m/%d',null=True)

and this is my views.py

@api_view(['POST'])
@permission_classes ([AllowAny] , )
def addproduct(request,pk):
    data = request.data
    product = Product(
        price = data['price'],
        device_name = data['product_name'],
        photo = data['photo'],
        user = Users.objects.get(id=pk) 
    )
    if product:
        product.save()
        serializer = ProductSerializer(product,many=False)
        return Response(serializer.data)
    else:
        return Response({'error':'4'})

It works fine when it comes to fetching data (products I created in the Django admin) but how to send a JSON request that also contains the images and the other data ,NOTE: my views is function_based

afaf
  • 3
  • 3
  • 1
    If you want to use JSON then your best bet would be to convert image into base64 encoded string. Otherwise, send your image as multipart/form-data. – intelis Aug 09 '22 at 21:51
  • why not send `url` for image and when JavaScript put this url in `` then browser will load it. If you need to send data from file then standard method is to convert image into `base64` - and later use JavaScript to add url with `` – furas Aug 10 '22 at 08:26

0 Answers0