5

I add a JSONField for one of my models. I want to create an instance of that model in admin panel but that JSONField returns a validation error (Enter a valid JSON.)

how I can fix this??

model:

class Product(models.Model):
    category = models.ManyToManyField(Category, related_name='products')
    name = models.CharField(max_length=500)
    slug = models.SlugField(max_length=500, allow_unicode=True, unique=True)
    image_1 = models.ImageField(upload_to='products_pic/%Y/%m/%d/', null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    attribute = models.JSONField(default={})
    price = models.PositiveIntegerField()
    discount = models.PositiveIntegerField(null=True, blank=True)
    available = models.BooleanField(default=True)
    popular = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    comments = GenericRelation(Comment)

    class Meta:
        ordering = ('-created',)

    def __str__(self):
        return self.name

I add products in admin panel. I want to have multiple attributes for my products like color , size and ... . is it true to use json fiels for that??

this is the error:enter image description here

  • You should set `default=dict` not `default={}`, unless you want to share dictionary between all created instances of the same worker. You probably want a new dict each time, which is what `dict` will return when called with no args. – run_the_race Sep 13 '22 at 10:33

1 Answers1

7

This is not valid JSON. The strings in JSON are wrapped with double quotes. Indeed, you can verify this for example with JSONLint.com. It is a valid Python dictionary, but not valid JSON.

You thus should enter:

{ "key": "value" }

For more information, see the JSON specifications.

I add products in admin panel. I want to have multiple attributes for my products like color , size and ... . is it true to use json fiels for that??

If the fields are fixed (are attributes of all Products), then you should use individual fields, since that is more convenient to fielter, make forms, etc. If the data is more dynamic, it is often better to make use of a JSON field.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555