So, what i’m tryna do here is set the status of an object based on the length of m2m field.
Here’s how it looks
from django.db import models
class Dependency(models.Model):
dependency = models.SlugField('Шаблон')
class Seo(models.Model):
statuses = (
(1, 'Дефолтный'),
(2, 'Дополнительный')
)
dependencies = models.ManyToManyField(
Dependency,
verbose_name='Зависимости',
blank=True,
help_text='Оставьте пустым, если это дефолтный шаблон'
)
h1 = models.CharField('Заголовок(h1)', max_length=200)
title = models.CharField('Заголовок(title)', max_length=200)
description = models.CharField('Описание', max_length=200)
keywords = models.TextField('Ключевые слова')
status = models.IntegerField('Статус', choices=statuses, blank=True, editable=False)
def save(self, *args, **kwargs):
if len(self.dependencies) == 0:
self.status = 1
else:
self.status = 2
# self.status = 1
#
# print(len(self.dependencies))
super().save(*args, **kwargs)
class Page(models.Model):
pass
But it throws me an error that goes like
ValueError: "<Seo: Seo object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used.
And what it want to achieve is whenever the dependency field is empty then status should be 1 and otherwise it should be 2. But i couldn’t find a way to do it.
2
Answers
So, after several hours googling and just melt-functioning i had a thought that just popped right into my brain, what if i google something like "django m2m validation" and i got it. after reading django docs and this Django ManyToMany model validation i managed to get it working.
but still for me it is indeed crazy why django has no m2m sort of saving and validation kinda thing by default. Here goes the code. admin.pyforms.py
models.py
I think you can use Django database transactions.
Hope it could help.