2 questions:
- How can I stop duplicate creation if parent = None and the name is the same?
- Can I name a model method from a form?
See below for more details.
models.py
class MyTest(models.Model): parent = models.ForeignKey('self', null=True, blank=True, related_name='children') name = models.CharField(max_length=50) slug = models.SlugField(max_length=255, blank=True, unique=True) owner = models.ForeignKey(User, null=True) class Meta: unique_together = ("parent", "name") def save(self, *args, **kwargs): self.slug = self.make_slug() super(MyTest, self).save(*args, **kwargs) def make_slug(self):
note: slug = unique, too!
forms.py
class MyTestForm(forms.ModelForm): class Meta: model = MyTest exclude = ('slug',) def clean_name(self): name = self.cleaned_data.get("name") parent = self.cleaned_data.get("parent") if parent is None:
More details
The unique_together contract unique_together fine with the form when parent != None . However, when parent == None (null) allows duplicates.
To try to avoid this, I tried to use the form and the specific name clean_ to try to check for duplicates. This works when creating new objects, but does not work when modifying existing objects.
Someone mentioned that I should use commit = False on ModelForm.save, but I could not figure out how to do this / implement it. I also thought about using ModelForm has_changed to detect changes to the model and resolve them, but has_changed returns true for newly created objects with a form. help!
Also (a slightly different question) can I access the make_slug () model method from the form? I believe that currently my line exclude = ('slug',) also ignores the โuniqueโ restriction in the slug field, and in the model save field I generate slug instead. I was wondering if I can do this in forms.py instead?
django django-models django-forms
lostincode
source share