I am having a problem with trying to use CreateView, and then calling methods on the model, because the instance attribute is None until too late in the form process. Suppose this setup:
class Parent(models.Model):
pass
class Child(models.Model):
parent = models.ForeignKey(Parent, on_delete=models.CASCADE)
def clean(self):
if self.parent.pk == 1:
raise ValidationError("Parent 1 can't have children, because reasons")
views.py:
class ChildCreate(CreateView)
model = child
fields = []
The problem is that “parent” is not set anywhere in this workflow. As a result when the form is ready to save() it throws a “Parent is None” error.
I can fix this by overriding form_valid() in views.py:
class ChildCreate(CreateView)
model = child
fields = []
def form_valid(self, form):
# copy url PK to the form so it has the value attached
form.instance.parent_id = self.kwargs["pk"]
return super().form_valid(form);
…but this does not fix the problem with the clean() method in models.py, because that is getting called before form_valid.
Where is the proper place to set the parent ID for the new child, so it’s available for clean and save methods?