J
J
joli2019-04-05 18:21:30
Django
joli, 2019-04-05 18:21:30

Exception when adding a product?

An exception occurs (NOT NULL constraint failed: market_product.fk_market_id), when I add a product to the store through the form. If null=True is set in the fk_market field, then there is no error, but the connection of the product with the store is not established and you need to do this through the admin panel

class Market(models.Model):
    category = models.ForeignKey(Category, on_delete=models.PROTECT)
    slug = models.SlugField(max_length=20, unique=True, db_index=True)
    name = models.CharField(max_length=30, unique=True, db_index=True)
    published = models.DateTimeField(default=timezone.now)
    seller = models.ForeignKey(Profile, on_delete=models.CASCADE)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Market, self).save(*args, **kwargs)

    def __str__(self):
        return self.name


class Product(models.Model):
    fk_market = models.ForeignKey(Market, on_delete=models.CASCADE)
    name_product = models.CharField(max_length=40, db_index=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    image = models.ImageField(upload_to='products/%Y/%m/%d', null=True)
    description = models.TextField(max_length=200, blank=True)
    slug = models.SlugField(max_length=40, db_index=True)
    created = models.DateTimeField(auto_now_add=True)
    available = models.BooleanField(default=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name_product)
        super(Product, self).save(*args, **kwargs)

    def __str__(self):
        return self.name_product

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yura Khlyan, 2019-04-05
@joli

It is possible to create in the form through obj = form.save(commit=False)then to add communication and again to save.

J
joli, 2019-04-05
@joli

If someone has a similar problem, then you can link the models in this way

def market_detail(request, slug):
    market = get_object_or_404(Market, slug=slug)
    products = Product.objects.filter(fk_market__slug = slug)
    add = Market.objects.get(slug=slug)

    if request.method == 'POST':
        add_product = AddProductForm(request.POST)
        if add_product.is_valid():
            obj = add_product.save(commit=False)
            obj.fk_market = add
            obj.save()
            return redirect('/')
    else:
        add_product = AddProductForm()
    return render(request, 'market/market_detail.html', {'market': market,
                                                        'add_product': add_product,
                                                        'products': products})

PS But why the link is not created automatically and you need to do it in the view, I still do not understand, I would be grateful if you explain

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question