Hello everyone! I have overrided method “save” in the form class to not lose existing related objects in ManyToManyField works of model Work and for good practice. But as you can see, 10th line in code of save() method does the absurd thing: blank value of name field is valid.
models.py:
class Work(models.Model):
name = models.TextField(verbose_name='Name of work', max_length=1000)
works = models.ManyToManyField('self', verbose_name='Work's objects', blank=True, default=list)
select_type = models.CharField(verbose_name="Type of variant", max_length=11, choices=SelectTypes.choices, default=description('radio'))
class Meta:
verbose_name = 'Work'
verbose_name_plural = 'Works'
def __str__(self,):
return f"{self.name}"
forms.py:
class WorkForm(forms.ModelForm):
class Meta:
model = Work
fields = ('name', 'works')
labels = {'name': 'Название работы', 'works': 'Составные компоненты'}
def save(self, commit=True):
instance = super(WorkForm, self).save(commit=False)
work_set = []
if instance.id:
work_set.extend(instance.works.all())
if commit:
self.save_m2m()
instance.save()
instance.works.add(*work_set)
return instance
AddWorkComponents = modelformset_factory(
Work,
form=WorkForm,
extra=1,
can_delete=True,
fields=('name',),
labels={'name': 'Input a variant of the work'},
widgets={'name': forms.TextInput(attrs={'class': 'form-control'})}
)
In html extra forms which aren’t have filled don’t have value attribute.:
<input type="text" name="form-2-name" class="form-control" maxlength="1000" id="id_form-2-name">
As i figure out this instruction:
super(WorkForm, self)
creates a new object with overrided attributes (but not methods) in the basic class for WorkForm. Attributes will have those values, which are in a derived class. But i don’t know that absurd with validation field.