related question: Test if Django ModelForm has instance
According to the question&answer above, we can check if a modelform has instance as hasattr(form.instance, 'pk')
, because instance
must have pk
.
I misunderstood the related question. it says
Try checking if
form.instance.pk
isNone
.
But in my case where the model's primary key is customized as:
class MyModel(Model):
myid = models.CharField(max_length=10, primary_key=True)
...
And the modelform:
class MyModelForm(ModelForm):
class Meta:
model = MyModel
has pk
attribute on instance, after is_valid()
:
data = {'myid': '123'}
form = MyModelForm(data=data, instance=None)
form.is_valid()
if form.instance.pk is not None:
print('detect: modelform received an instance')
else:
print('detect: modelform didnt receive an instance')
My question is:
In this case, how to check if a modelform was set with an existing instance?
Or, how to check if the mode of modelform is "edit on existed entry" / "new entry to our DB"?