Let's say we have two models.class Tag(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Post(models.Model):
tags = models.ManyToManyField(Tag, blank=True)
def __str__(self):
return str(self.tags.all())
We can implement your behavior in a few ways.When editing, make the tags field automatically complete by all Tag models and allow the user to delete anything if necessary. In order to achieve this, we will redesign in the form described below. initTo make sure that if the new post is retained, if the user has not indicated anything in the tag field, it is automatically filled. In order to achieve this, we will redesign in shape. cleanclass PostAdminForm(ModelForm):
def init(self, *args, **kwargs):
if kwargs.get('instance') is None:
initial = kwargs.get('initial', {})
initial['tags'] = Tag.objects.all()
super().init(*args, **kwargs)
def clean(self):
cleaned_data = super().clean()
if self.instance.pk is None and not cleaned_data.get('tags'):
cleaned_data['tags'] = Tag.objects.all()
return cleaned_data
class Meta:
model = Post
fields = '__all__'
In this case, as the form contains both reassigned methods, the behaviour described in paragraph 1 and paragraph 2 will be maintained. If you need only one way, you can remove the extra method for you.You can use this form for editing both in the adminka and in the usual view.