milan milan - 2 years ago 154
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)

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

class ProductSerializers(ModelSerializer):
image = ProductImageSerializer(many=False,read_only=True)
class Meta:
model = Product

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

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 =['file']
print ('file_obj',file_obj)
return Response(status=204)

def perform_create(self, serializer):
print('then perform works')

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download