I am trying to determine if the admin screen in Django is add or change in the save method. If I internet search on this, I cannot find any answer. What is the proper way to do this in Python?
Asked
Active
Viewed 1,022 times
3 Answers
2
An object has a primary key that is not None
in case you update the model, so you can check this, for example with:
class MyModelAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if obj.pk is None:
# add
pass
else:
# change
super().save_model(request, obj, form, change)

Willem Van Onsem
- 443,496
- 30
- 428
- 555
1
As with ModelForms, you can use a similar trick:
def save_model(self, request, obj, form, change):
if obj._state.adding:
# Adding
else:
# Editing
super().save_model(request, obj, form, change)

j4n7
- 590
- 7
- 9
0
We can check self.instance but just before super().init() is called. Try out my solution https://stackoverflow.com/a/70845558/15080117

Ivan Vinitskyi
- 71
- 1
- 2
-
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/30902279) – Flair Jan 29 '22 at 06:24