2

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 is None.


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"?

Community
  • 1
  • 1
keisuke
  • 2,123
  • 4
  • 20
  • 31

1 Answers1

3

If your model has a primary key column, than pk property of that model will always be there and be an alias to that field.

In your case you do not want to check if your form.instance has a property named pk (that's the hasattr line). Instead you have to check if the property pk of form.instance is empty or not:

data = {'myid': '123'}
form = MyModelForm(data=data, instance=None)
form.is_valid()
if form.instance.pk: 
     print('This has a pk! It was saved before!')
else:
     print('This has no pk! It was never saved!')

If it is a new model, not yet saved, than the form.instance.pk field's value will be u'' (empty string), which evaluates to False in if statement, which does what you what it to.

Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162