hossein-shahsavan
hossein-shahsavan

Reputation: 359

django JSONField doesn't accept value

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

Upvotes: 5

Views: 5003

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

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.

Upvotes: 9

Related Questions