milan milan - 4 months ago 21
Python Question

Why my CreateAPIView does not show Product and store category field?

I am designing an API for listing stores and create store. I could list store but while designing for creating store I am not getting product and store category field inspite of calling all Product and Store category serializer in Store Serializer.

My shortened models look like

class Merchant(models.Model):
user = models.ForeignKey(User)
phone = models.PositiveIntegerField(null=True,blank=True)

class Store(models.Model):
merchant = models.ForeignKey(Merchant)
name_of_legal_entity = models.CharField(max_length=250)

class Product(models.Model):
store = models.ForeignKey(Store)
image = models.ForeignKey('ProductImage',blank=True,null=True)
name_of_product = models.CharField(max_length=120)

class ProductImage(models.Model):
image = models.ImageField(upload_to='products/images/')

class StoreCategory(models.Model):
product = models.ForeignKey(Product,null=True, on_delete=models.CASCADE,related_name="store_category")
store_category = models.CharField(choices=STORE_CATEGORIES, default='GROCERY', max_length=10)


Serializer.py

class ProductImageSerializer(ModelSerializer):
class Meta:
model = ProductImage
fields = ( 'id','imageName', )

class ProductSerializers(ModelSerializer):
image = ProductImageSerializer(many=False,read_only=True)
class Meta:
model = Product
fields=('id','image','name_of_product','description','price','active',)

class StoreCategorySerializer(ModelSerializer):
product = ProductSerializers(read_only=True)
class Meta:
model = StoreCategory

class StoreSerializer(ModelSerializer):
# url = HyperlinkedIdentityField(view_name='stores_detail_api')
store_categories = StoreCategorySerializer(many=True)
merchant = MerchantSerializer(read_only=True)
class Meta:
model = Store
fields=("id",
"merchant",
"store_categories",
"name_of_legal_entity",
"pan_number",
"registered_office_address",
"name_of_store",
)


Views.py

class StoreCreateAPIView(CreateAPIView):
queryset = Store.objects.all()
serializer_class = StoreSerializer
parser_classes = (FormParser,MultiPartParser,)

def put(self, request, filename, format=None):
print('first put works')
file_obj = request.data['file']
print ('file_obj',file_obj)
return Response(status=204)

def perform_create(self, serializer):
print('then perform works')
serializer.save(user=self.request.user)


Here is the screenshot of how it looks

enter image description here

Why it is not showing Merchant, Product and Store Category in the form?

Answer

Remove read_only=True from the serializers that you wanna create entry of. Like:

product = ProductSerializers(read_only=True)

should be

product = ProductSerializers()

read_only will prevent it from written therefore i wont be in the outcome.